printbob.py:
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.
This is the wrong approach.
You should refactor printbob.py
so that it can be imported by other python modules. This version can be imported and 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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.