>>> subprocess.call(["ls", "-l"])
0
>>> subprocess.call("exit 1", shell=True)
1
python
x=subprocess.check_output(["echo", "Hello World!"],shell=True)
print(x)
"Hello World!"
shell
y=subprocess.check_output(["type", "app2.cpp"],shell=True)
print(y)
#include
using namespace std;
......
網絡
handle = open(r'd:\tmp.log','wt')
subprocess.Popen(['ipconfig','-all'], stdout=handle)
app
output = subprocess.Popen(['ipconfig','-all'], stdout=subprocess.PIPE,shell=True)
oc=output.communicate() #取出output中的字符串
#communicate() returns a tuple (stdoutdata, stderrdata).
print(oc[0]) #打印網絡信息
Windows IP Configuration
Host Name . . . . .
性能
由於communicate通訊一次以後即關閉了管道.這時能夠試試下面的方法:
p= subprocess.Popen(["wc"], stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
p.stdin.write('your command')
p.stdin.flush()
#......do something
try:
#......do something
p.stdout.readline()
#......do something
except:
print('IOError')
#......do something more
p.stdin.write('your other command')
p.stdin.flush()
#......do something more
spa
其實在python中,和shell腳本,其餘程序交互的方式有不少,好比:
os.system(cmd),os.system只是執行一個shell命令,不能輸入、且無返回
os.open(cmd),能夠交互,可是是一次性的,調用都少次都會建立和銷燬多少次進程,性能太差線程
import subprocess
p = subprocess.Popen('ls') code
import subprocess
p = subprocess.Popen('ls',stdout=subprocess.PIPE)
print p.stdout.readlines() 進程
父進程發送'say hi',子進程輸出 test say hi,父進程獲取輸出並打印
#test1.py
import sys
line = sys.stdin.readline()
print 'test',line
#run.py
from subprocess import *
p =Popen('./test1.py',stdin=PIPE,stdout=PIPE)
p.stdin.write('say hi/n')
print p.stdout.readline()
#result
test say hi
ip
# test.py
import sys
while True:
line = sys.stdin.readline()
if not line:break
sys.stdout.write(line)
sys.stdout.flush()
# run.py
import sys
from subprocess import *
proc = Popen('./test.py',stdin=PIPE,stdout=PIPE,shell=True)
for line in sys.stdin:
proc.stdin.write(line)
proc.stdin.flush()
output = proc.stdout.readline()
sys.stdout.write(output)
注意,run.py的flush和test.py中的flush,要記得清空緩衝區,不然程序得不到正確的輸入和輸出
import subprocess
def main():
process1 = subprocess.Popen("python -u sub.py", shell=False, stdout = subprocess.PIPE, stderr=subprocess.STDOUT)
#print process1.communicate()[0]
while True:
line = process1.stdout.readline()
if not line:
break
print line
if __name__ == '__main__':
main()
import subprocess import time p = subprocess.Popen('ping 127.0.0.1 -n 10', stdout=subprocess.PIPE) while p.poll() == None: print p.stdout.readline() time.sleep(1) print p.stdout.read() print 'returen code:', p.returncode