开发者

Get output of python script from within python script

printbob.p开发者_StackOverflow社区y:

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

I get:

  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

What am I doing wrong here? I just want to get the output of another python script inside of another python script. Do I need to call cmd.exe or can I just run printbob.py and send commands to it?


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

There must be a better way of doing it though, since the script is also in Python. It's better to find some way to leverage that than what you're doing.


There is likely to be a better approach.

Consider refactoring printbob.py so that it can be imported by other Python modules. This version can be imported or called from the command-line:

#!/usr/bin/env python

import sys

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

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

Here it is called from the command-line:

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

Now we can import it in getbob.py:

#!/usr/bin/env python

import printbob

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

Here it is running:

python getbob.py 
arg1
arg2
arg3
arg4

See also What does if __name__ == "__main__": do? for more detail of this Python idiom.


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

Just wrap all arguments in a string and give 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]


The subprocess.run() function was added in Python 3.5.

import subprocess

cmd = subprocess.run(["ls", "-ashl"], capture_output=True)
stdout = cmd.stdout.decode()  # bytes => str

refer: PEP 324 – PEP proposing the subprocess module

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜