I am just starting with python so I am struggling with a quite simple example. Basically I want pass the name of an executable plus its input via the command line arguments, e.g.:
python myprogram refprogram.exe refinput.txt
That means when executing myprogram
, it executes refprogram.exe
and passes to it as argument refinput
. I tried to do it the following way:
import sys, string, os
print sys.argv
res = os.system(sys.argv(1)) sys.argv(2)
print res
The error message that I get is:
res = os.system(sys.argv(1)) sys.argv(2)
^
SyntaxError: invalid syntax
Anyone an idea what I am doing wrong?
I am running Python 2.7
sys.argv
is a list, and is indexed using square brackets, e.g.sys.argv[1]
. You may want to checklen(sys.argv)
before indexing it as well.Also, if you wanted to pass parameters to
os.system()
, you might want something likeos.system(' '.join(sys.argv[1:]))
, but this won't work for arguments with spaces. You're better off using the subprocess module.If you are running Python 2.7 it is recommended to use the new
subprocess
module.In this case you would write
This line
Is wrong in a couple of ways.
First, sys.argv is a list, so you use square brackets to access its contents:
Second, you close out your parentheses on
os.system
too soon, andsys.argv(2)
is left hanging off of the end of it. You want to move the closing parenthesis out to the very end of the line, after all of the arguments.Third, you need to separate the arguments with commas, a simple space won't do.
Your final line should look like this:
sys.argv is a list
A far, far better way to do this is with the argparse library. The envoy wrapper library makes subprocess easier to work with as well.
A simple example:
This reads in the arguments, parses them, then sends them to the main method as a dictionary of keywords and values. That lets you test your main method independently from your argument code, by passing in a preconstructed dictionary.
The main method prints out the keywords and values. Then it creates a command string, and passes that to envoy to run. Finally, it prints the output from the command.
If you have pip installed, envoy can be installed with
pip install envoy
. The easiest way to get pip is with the pip-installer.