I use python to create my project settings setup, but I need help getting the command line arguments.
I tried this on the terminal:
$python myfile.py var1 var2 var3
In my Python file, I want to use all variables that are input.
I use python to create my project settings setup, but I need help getting the command line arguments.
I tried this on the terminal:
$python myfile.py var1 var2 var3
In my Python file, I want to use all variables that are input.
Some additional things that I can think of.
As @allsyed said sys.argv gives a list of components (including program name), so if you want to know the number of elements passed through command line you can use len() to determine it. Based on this, you can design exception/error messages if user didn't pass specific number of parameters.
Also if you looking for a better way to handle command line arguments, I would suggest you look at https://docs.python.org/2/howto/argparse.html
You can use
sys.argv
to get the arguments as a list.If you need to access individual elements, you can use
where
i
is index,0
will give you the python filename being executed. Any index after that are the arguments passed.I highly recommend
argparse
which comes with Python 2.7 and later.The
argparse
module reduces boiler plate code and makes your code more robust, because the module handles all standard use cases (including subcommands), generates the help and usage for you, checks and sanitize the user input - all stuff you have to worry about when you are usingsys.argv
approach. And it is for free (built-in).Here a small example:
and the output for
python prog.py -h
and for
python prog.py 1
as you would expect:Python tutorial explains it:
More specifically, if you run
python example.py one two three
:will give you a list of arguments (not including the name of the python file)
If you call it like this:
$ python myfile.py var1 var2 var3
Similar to arrays you also have
sys.argv[0]
which is always the current working directory.