I have found documentation about subprocess.check_output() but I cannot find one with arguments and the documentation is not very in depth. I am using Python 3 (but am trying to run a Python 2 file through Python 3)
I am trying to run this command:
python py2.py -i test.txt
-i is a positional argument for argparse, test.txt is what the -i is, py2.py is the file to run
I have tried a lot of (non working) variations including:
py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])
py2output = subprocess.check_output([str('python'),'py2.py','-i', test.txt'])
This question is related to
python
python-3.x
python-2.x
Since Python 3.5, subprocess.run() is recommended over subprocess.check_output():
>>> subprocess.run(['cat','/tmp/text.txt'], stdout=subprocess.PIPE).stdout
b'First line\nSecond line\n'
Since Python 3.7, instead of the above, you can use capture_output=true
parameter to capture stdout and stderr:
>>> subprocess.run(['cat','/tmp/text.txt'], capture_output=True).stdout
b'First line\nSecond line\n'
Also, you may want to use universal_newlines=True
or its equivalent since Python 3.7 text=True
to work with text instead of binary:
>>> stdout = subprocess.run(['cat', '/tmp/text.txt'], capture_output=True, text=True).stdout
>>> print(stdout)
First line
Second line
See subprocess.run() documentation for more information.
Adding on to the one mentioned by @abarnert
a better one is to catch the exception
import subprocess
try:
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'],stderr= subprocess.STDOUT)
#print('py2 said:', py2output)
print "here"
except subprocess.CalledProcessError as e:
print "Calledprocerr"
this stderr= subprocess.STDOUT is for making sure you dont get the filenotfound error in stderr- which cant be usually caught in filenotfoundexception, else you would end up getting
python: can't open file 'py2.py': [Errno 2] No such file or directory
Infact a better solution to this might be to check, whether the file/scripts exist and then to run the file/script
Source: Stackoverflow.com