using p.open and p.communicate example

Here is the code to try out, code2.py :

#!/usr/bin/python
import subprocess
p = subprocess.Popen('tr a-z A-Z',shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
out,err = p.communicate("python")
print out

OUTPUT:
[root@devine ~]# ./code2.py
PYTHON

Advertisements

Python subprocess examples

Here is the code for testing subprocess in python, firstcode.py

When this python program runs,the output will be send to standard output,stdout . For managing process Python 2.4 provides a special module called – subprocess and a class called Popen.

#!/usr/bin/python
import subprocess
p = subprocess.Popen('df -h',shell=True, stdout=subprocess.PIPE)
out,err = p.communicate()
print out

OUTPUT

[root@devine ~]# ./firstcode.py
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/vg_devine-lv_root
18G 3.5G 13G 22% /
tmpfs 497M 276K 497M 1% /dev/shm
/dev/sda1 485M 33M 428M 8% /boot