Python 通过Popen执行模块
我正在执行一个模块popen1.py,该模块使用子流程模块调用popen2.py 但是没有显示popen2.py的输出..当我显示子进程id时,会显示它..在哪里为popen2.py打印输出 召唤Python 通过Popen执行模块,python,Python,我正在执行一个模块popen1.py,该模块使用子流程模块调用popen2.py 但是没有显示popen2.py的输出..当我显示子进程id时,会显示它..在哪里为popen2.py打印输出 召唤 流程完成后,您可以读取child.stdout和child.stderr以获取数据(因为您通过了子流程管道) 或者,您可以使用oudata,errdata=child.communicate(),它将等待子流程完成,然后将其输出为字符串 从设计的角度来看,最好是导入。我将重构popen2.py,如下
流程完成后,您可以读取
child.stdout
和child.stderr
以获取数据(因为您通过了子流程管道
)
或者,您可以使用oudata,errdata=child.communicate()
,它将等待子流程完成,然后将其输出为字符串
从设计的角度来看,最好是导入。我将重构popen2.py,如下所示:
#popen2.py
# ... stuff here
def run(*argv):
#...
if __name__ == '__main__':
import sys
run(sys.argv[1:])
然后您可以在popen1.py中导入并运行popen2.py:
#popen1.py
import popen2
popen2.run("parm1=test","parm=test1")
您可以使用child.stdout/child.stdin与进程通信:
child = subprocess.Popen(['python', 'popen2.py',"parm1='test'","parm='test1'"], shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print child.stdout.readlines()
如果您是从python执行python代码,为什么不
execfile
或import
?第二个过程真的是吗necessary@tmc:我可以使用execfile传递参数吗?您不必使用参数;您读入的脚本将有权访问本地命名空间及其变量。我需要在外部传递参数。输出为空。我如何知道模块是否在第一位被调用..我在代码中没有看到任何错误
child = subprocess.Popen(['python', 'popen2.py',"parm1='test'","parm='test1'"], shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print child.stdout.readlines()