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.
option. You can test command line arguments by running an executable from the "Command Prompt" in Windows or from the "DOS prompt" in older versions of Windows. You can also use command line arguments in program shortcuts, or when running an application by using Start -> Run.
A command line argument is simply anything we enter after the executable name, which in the above example is notepad.exe. So for example, if we launched Notepad using the command C:\Windows\System32\notepad.exe /s, then /s would be the command line argument we used.
Using '$@' for reading command-line arguments: The command-line arguments can be read without using argument variables or getopts options. Using '$@' with the first bracket is another way to read all command-line argument values.
Command line syntax Commands provide the action, or list of actions separated by semicolons, that should be implemented. If no command is specified, then the command is assumed to be new-tab by default. To display a help message listing the available command line arguments, enter: wt -h , wt --help , wt -? , or wt /? .
Python tutorial explains it:
import sys
print(sys.argv)
More specifically, if you run python example.py one two three
:
>>> import sys
>>> print(sys.argv)
['example.py', 'one', 'two', 'three']
(not including the name of the Python file)
import sys
sys.argv[1:]
The [1:]
is a slice starting from the second element (index 1) and going to the end of the arguments list. This is because the first element is the name of the Python file, and we want to remove that.
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 using sys.argv
approach. And it is for free (built-in).
Here a small example:
import argparse
parser = argparse.ArgumentParser("simple_example")
parser.add_argument("counter", help="An integer will be increased by 1 and printed.", type=int)
args = parser.parse_args()
print(args.counter + 1)
and the output for python prog.py -h
usage: simple_example [-h] counter
positional arguments:
counter counter will be increased by 1 and printed.
optional arguments:
-h, --help show this help message and exit
and the output for python prog.py 1
As one would expect:
2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With