I want to run the following command from within a Python program:
python py2.py -i test.txt
I tried using subprocess.check_output as follows:
py2output = subprocess.check_output(['python py2.py', '-i', 'test.txt'])
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
The right answer (using Python 2.7 and later, since
check_output()was introduced then) is:To demonstrate, here are my two programs:
py2.py:
py3.py:
Running it:
Here’s what’s wrong with each of your versions:
First,
str('python py2.py')is exactly the same thing as'python py2.py'—you’re taking astr, and callingstrto convert it to anstr. This makes the code harder to read, longer, and even slower, without adding any benefit.More seriously,
python py2.pycan’t be a single argument, unless you’re actually trying to run a program named, say,/usr/bin/python\ py2.py. Which you’re not; you’re trying to run, say,/usr/bin/pythonwith first argumentpy2.py. So, you need to make them separate elements in the list.Your second version fixes that, but you’re missing the
'beforetest.txt'. This should give you aSyntaxError, probably sayingEOL while scanning string literal.Meanwhile, I’m not sure how you found documentation but couldn’t find any examples with arguments. The very first example is:
That calls the
"echo"command with an additional argument,"Hello World!".Also:
I’m pretty sure
-iis not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.