2011-05-22 81 views
9

printbob.py:获取python脚本的输出从Python脚本中

import sys 
for arg in sys.argv: 
    print arg 

getbob.py

import subprocess 
#printbob.py will always be in root of getbob.py 
#a sample of sending commands to printbob.py is: 
#printboby.py arg1 arg2 arg3 (commands are seperated by spaces) 

print subprocess.Popen(['printbob.py', 'arg1 arg2 arg3 arg4']).wait() 

x = raw_input('done') 

我得到:

File "C:\Python27\lib\subprocess.py", line 672, in __init__ 
    errread, errwrite) 
    File "C:\Python27\lib\subprocess.py", line 882, in _execute_child 
    startupinfo) 
WindowsError: [Error 193] %1 is not a valid Win32 application 

我在做什么错在这里? 我只想得到另一个python脚本内的另一个python脚本的输出。 我是否需要调用cmd.exe,或者我可以运行printbob.py并将命令发送给它?

回答

8
proc = subprocess.Popen(['python', 'printbob.py', 'arg1 arg2 arg3 arg4'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
print proc.communicate()[0] 

尽管这样做一定有更好的方法,因为脚本也在Python中。找到某种方式来利用这一点比你所做的更好。

+1

回溯(最后最近一次调用): 文件 “”,1号线,在 subprocess.STDIN AttributeError的: '模块'对象没有属性'STDIN' – MistahX 2011-05-22 04:58:51

+1

意思标准输出 - 固定。 – rfw 2011-05-22 05:03:55

+0

我不得不将arg1 arg2分成不同的comman分隔字符串,就像'['python','printbob.py','arg1','arg2']' – Quinma 2014-01-17 22:44:26

2

这是错误的方法。

你应该重构printbob.py,以便它可以被其他python模块导入。这个版本可以导入并通过命令行调用:

python printbob.py one two three four five 
printbob.py 
one 
two 
three 
four 
five 

现在,我们可以getbob.py导入:

#!/usr/bin/env python 

import printbob 

printbob.main('arg1 arg2 arg3 arg4'.split(' ')) 

#!/usr/bin/env python 

import sys 

def main(args): 
    for arg in args: 
     print(arg) 

if __name__ == '__main__': 
    main(sys.argv) 

这是通过命令行调用

运行中:

python getbob.py 
arg1 
arg2 
arg3 
arg4 
+0

谢谢你的回答,但我正在寻找一种方法来运行python代码不在同一个实例中...因为某些线程奇怪的行为,但是导入脚本通常是在另一个脚本中访问代码的最佳方式。 – MistahX 2011-05-22 05:10:35

+1

@MistahX:你奇怪的线程行为让你觉得解释器的一个新实例就是听起来有趣的方式。可能有更好的方法来解决它。但这是一个全新的问题! – Johnsyweb 2011-05-22 05:19:43

0

The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence

只是包装在一个字符串的所有参数,并给shell=True

proc = subprocess.Popen("python myScript.py --alpha=arg1 -b arg2 arg3" ,stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) 
print proc.communicate()[0]