[python] subprocess module

1.subprocess.Popen

Popen will enable a child-process and parent process in parallel.

  • subprocess.Popen(['type','test.py'],shell=True)
  • subprocess.Popen('tpye test.py',shell=True)
1 def TestPopen():
2   import subprocess
3   #p=subprocess.Popen("type test.py",shell=True)
4   p=subprocess.Popen(["type","test.py"],shell=True) #another way to invoke args
5 TestPopen()

Tip&Tricks

 1 import shlex
 2 def shlex_split(input = 'SH is a beautiful city'):
 3     output = shlex.split(input)#shlex module is delimited with space by default
 4     #split() is used to convert string to the list of string
 5     print output
 6 
 7 shlex_split()
 8 
 9 #output:
10 #['SH', 'is', 'a', 'beautiful', 'city']

2 subprocess.call

1 def test_call():
2     import subprocess
3     #p=subprocess.call("type test.py",shell=True)
4     p=subprocess.call(["type","test.py"],shell=True)#another way to invoke args
5     #equivalent to p=subprocess.Popen(["type","test.py"],shell=True)
6     #p.wait()
7     #print p.returncode
8     print p
9 test_call()

 3 subprocess.PIPE

1 import subprocess
2 def test_PIPE():
3     proc=subprocess.Popen(['type','test.py'],shell=True,stdout=subprocess.PIPE)
4     output=proc.stdout.readlines()
5     print output #list of string of each line
6     for line in output:
7         print line
8 
9 test_PIPE()

 

 4 proc.communicate(input=None)

 1 import subprocess
 2 def test_communicate():
 3     proc = subprocess.Popen(['type','test.py'],shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
 4     (stdoutdata,stderrdata) = proc.communicate()
 5     print stdoutdata # string 
 6     #print stderrdata
 7     if proc.returncode!=0:
 8         print 'subprocess error'
 9     for line in stdoutdata.split('\n'): #convert string to list of string
10         print line
11 test_communicate()

5 Subprocess.PIPE (con't)

 1 import subprocess
 2 def test_PIPE():
 3     proc1=subprocess.Popen(['type','test.py'],shell=True,stdin=subprocess.PIPE, stdout=subprocess.PIPE)
 4     proc2=subprocess.Popen(['findstr','/c:test_PIPE'],shell=True,stdin=proc1.stdout,stdout=subprocess.PIPE)
 5     #place proc1 output as proc2 input
 6     #search "test_PIPE" using findstr from test.py file
 7     output=proc2.communicate()[0]
 8     print output
 9 
10 test_PIPE()

6 MISC

  •  replace shell command

       p=`ls -l` is equivalent to p= subprocess.Popen(['ls','-l'],shell=True,stdout=subprocess.PIPE).communicate()[0]

  •  replace shell PIPE

       p=`dmesg|grep cpu` is idential with:

       p1=subprocess.Popen(['dmesg'],shell=True,stdout=subprocess.PIPE)

       P2=subprocess.Popen(['grep','cpu'],shell=True,stdin=p1.stdout,stdout=subprocess.PIPE).communicate()[0]

  

posted @ 2013-12-31 10:48  Yu Zi  阅读(372)  评论(0)    收藏  举报