从python scrip中获取python脚本的输出

2024-04-20 06:51:41 发布

您现在位置:Python中文网/ 问答频道 /正文

printbob.py版本:

import sys
for arg in sys.argv:
    print arg

获取bob.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并向它发送命令?


Tags: ofinpyimportissysargarg3
3条回答

这是错误的做法。

您应该重构printbob.py,以便其他python模块可以导入它。可以从命令行导入和调用此版本:

#!/usr/bin/env python

import sys

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

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

在这里,它是从命令行调用的:

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(' '))

它正在运行:

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

不过,必须有更好的方法来实现这一点,因为脚本也是用Python编写的。最好是找到一些方法来利用它,而不是你在做什么。

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]

相关问题 更多 >