Get output of python script from within python script

Question:

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:Python27libsubprocess.py", line 672, in __init__
    errread, errwrite)
  File "C:Python27libsubprocess.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?

Asked By: MistahX

||

Answers:

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.

Answered By: user193476

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.

Answered By: johnsyweb

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]
Answered By: Halil

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

Answered By: NicoNing
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.