hello.py代码如下:
#!/usr/bin/python
print "hello, world!"
TestInput.py代码如下:
#!/usr/bin/python
str = raw_input()
print("input string is: %s" % str)
这种方式只是执行shell命令,返回一个返回码(0表示执行成功,否则表示失败)
retcode = os.system("python hello.py")
print("retcode is: %s" % retcode);
输出:
hello, world!
retcode is: 0
执行命令并返回该执行命令程序的输入流或输出流.该命令只能操作单向流,与shell命令单向交互,不能双向交互.
fouput = os.popen("python hello.py")
result = fouput.readlines()
print("result is: %s" % result);
输出:
result is: [‘hello, world!\n‘]
finput = os.popen("python TestInput.py", "w")
finput.write("how are you\n")
输出:
input string is: how are you
类似os.system(),注意这里的”shell=True”表示用shell执行命令,而不是用默认的os.execvp()执行.
f = call("python hello.py", shell=True)
print f
输出:
hello, world!
0
利用Popen可以是实现双向流的通信,可以将一个程序的输出流发送到另外一个程序的输入流.
Popen()是Popen类的构造函数,communicate()返回元组(stdoutdata, stderrdata).
p1 = Popen("python hello.py", stdin = None, stdout = PIPE, shell=True)
p2 = Popen("python TestInput.py", stdin = p1.stdout, stdout = PIPE, shell=True)
print p2.communicate()[0]
#other way
#print p2.stdout.readlines()
输出:
input string is: hello, world!
#!/usr/bin/python
import os
from subprocess import Popen, PIPE, call
retcode = os.system("python hello.py")
print("retcode is: %s" % retcode);
fouput = os.popen("python hello.py")
result = fouput.readlines()
print("result is: %s" % result);
finput = os.popen("python TestInput.py", "w")
finput.write("how are you\n")
f = call("python hello.py", shell=True)
print f
p1 = Popen("python hello.py", stdin = None, stdout = PIPE, shell=True)
p2 = Popen("python TestInput.py", stdin = p1.stdout, stdout = PIPE, shell=True)
print p2.communicate()[0]
#other way
#print p2.stdout.readlines()
原文地址:http://blog.csdn.net/csujiangyu/article/details/44871759