Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sys.argv and argparse

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?

like image 611
Stephen Berndt Avatar asked Feb 12 '16 14:02

Stephen Berndt


People also ask

What is Argparse used for in Python?

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 .

Is Argparse part of Python?

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.

How do you pass arguments to Argparse Python?

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() .

How do I pass SYS argv in Python?

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.


2 Answers

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.

like image 167
mgilson Avatar answered Sep 30 '22 16:09

mgilson


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.

like image 21
Seekheart Avatar answered Sep 30 '22 15:09

Seekheart