我想了解Python的子进程模块是如何工作的,并且已经开始设置自己的一些问题,这些问题并不像我想的那么简单。具体来说,我试图与已经创建为子流程的Python intepreter进行交互。在使用Python的子进程模块作为子进程运行Python解释器时遇到问题
我创建了一个测试模块,dummy.py
即结构如下:
def hi():
print "Hi Earth"
hi()
然后,测试我使用的子模块的能力,我写了一个名为pyrun.py
模块,其被构造如下:
import subprocess
def subprocess_cmd1():
outFile = open("tempy1.tmp",'w')
proc = subprocess.Popen("pwd", stdin=subprocess.PIPE, stdout=outFile, stderr=outFile, shell=True)
outFile.close()
def subprocess_cmd2():
outFile = open("tempy2.tmp",'w')
proc = subprocess.Popen('python dummy.py', stdin=subprocess.PIPE, stdout=outFile, stderr=outFile, shell=True)
outFile.close()
def subprocess_cmd3():
outFile = open("tempy3.tmp",'w')
proc = subprocess.Popen('python', stdin=subprocess.PIPE, stdout=outFile, stderr=outFile, shell=True)
proc.communicate('import dummy')
outFile.close()
def subprocess_cmd4():
outFile = open("tempy4.tmp",'w')
proc = subprocess.Popen('python', stdin=subprocess.PIPE, stdout=outFile, stderr=outFile, shell=True)
proc.communicate('import dummy')
proc.communicate('dummy.hi()')
outFile.close()
print "Start"
subprocess_cmd1()
subprocess_cmd2()
subprocess_cmd3()
subprocess_cmd4()
print "Stop"
的想法是从调用进程发送输入到子进程,并已全部输出发送到一个文本文件中。
当我尝试在命令行中运行pyrun,我得到如下结果:
[email protected]:~/Projects/LushProjects/newCode$ python pyrun.py
Start
Traceback (most recent call last):
File "pyrun.py", line 42, in <module>
subprocess_cmd4()
File "pyrun.py", line 35, in subprocess_cmd4
proc.communicate('dummy.hi()')
File "/usr/lib/python2.7/subprocess.py", line 785, in communicate
self.stdin.write(input)
ValueError: I/O operation on closed file
subprocess_cmd1 - 3
运行没有崩溃。错误进来subprocess_cmd4()
,试图执行该语句时:
proc.communicate('dummy.hi()')
这似乎是因为communicate
方法关闭管道stdin
它是第一次使用后。它为什么这样做?假设管道应该关闭有什么好处吗?
而且,当我看着tempy3.tmp
(为subprocess_cmd3
我的输出文件),它缺少Python解释器的“启动”文本的内容 - 即
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
这是为什么?我重定向都stdout
& stderr
到outFile
。
最后,为什么tempy4.tmp
完全空?它至少不应该包含在它坠毁之前发送给它的文本? (即它应该看起来很像tempy3.tmp
)
无关:为什么要使用子进程来运行Python代码? – jfs
@ J.F.Sebastien - 我真的只是试验子过程,看看我是否理解如何使用它以及它是如何工作的。我想一个更现实的例子就是使用它来在其他语言的解释器中运行代码。 – user1245262
如果它是一个学习exersice那么这里有一些提示:1.避免'shell = True',使用列表参数来传递命令2.知道如果一个子进程的stdin/stdout/stderr被重定向(例如,在输出中抑制颜色(ansi代码)),或者在'python'中没有标题。 – jfs