Stephen Berndt
Stephen Berndt

Reputation: 433

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?

Upvotes: 29

Views: 26762

Answers (2)

mgilson
mgilson

Reputation: 310297

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.

Upvotes: 42

Seekheart
Seekheart

Reputation: 1173

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.

Upvotes: 7

Related Questions