I have been looking for ways to add argument values to a script when I run it from the command line. The two packages I have found that seem to do this are sys.argv and argparse.
I'd also like to be able to add some sort of help function if possible.
Can somebody explain the difference between the two, and perhaps what would be easier for someone starting out?
The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv .
The Python argparse library was released as part of the standard library with Python 3.2 on February the 20th, 2011. It was introduced with Python Enhancement Proposal 389 and is now the standard way to create a CLI in Python, both in 2.7 and 3.2+ versions.
After importing the library, argparse. ArgumentParser() initializes the parser so that you can start to add custom arguments. To add your arguments, use parser. add_argument() .
sys. argv is a list in Python, which contains the command-line arguments passed to the script. With the len(sys. argv) function you can count the number of arguments.
sys.argv
is simply a list of the commandline arguments.
argparse
is a full featured commandline parser which generally parses sys.argv
and gives you back the data in a much easier to use fashion.
If you're doing anything more complicated than a script that accepts a few required positional arguments, you'll want to use a parser. Depending on your python version, there are 3 available in the python standard library (getopt
, optparse
and argparse
) and argparse
is by far the best.
I would recommend you use argparse for your command line arguments for two reasons. Making an arg is very straight forward as pointed out in the documentation, and second because you want a help function argparse gives you it for free.
Documentation: https://docs.python.org/2/howto/argparse.html
Let me know if you need more help.
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