Python sys.argv and argparse
Solution 1
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.
Solution 2
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.
Related videos on Youtube
![Stephen Berndt](https://lh4.googleusercontent.com/-zJbiqELpfpQ/AAAAAAAAAAI/AAAAAAAAABE/Mrmt9jcbNbs/photo.jpg?sz=256)
Stephen Berndt
I'm a senior BI analyst for TUNE. Most of what I do revolves around making Tableau run as fast as possible. My biggest interest right now is using Python for data analysis.
Updated on June 22, 2022Comments
-
Stephen Berndt about 2 years
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?
-
vaultah over 8 years
sys.argv
is not a package. You'd useargparse
. -
khelwood over 8 years
sys.argv
is a list of arguments.argparse
is a package to help you deal with arguments (including adding a--help
argument). -
hpaulj over 8 years
sys.argv
is the list of strings derived from the commandline.argparse
lets you create a parser the can decodesys.argv
. For simple cases you can usesys.argv
directly.
-
-
Seekheart over 8 yearsI'm curious, is getopt the same getopt from perl's module?
-
chepner over 8 years@Seekheart More or less.
getopt
is the standard POSIX library for parsing command line options, and many languages provide a wrapper or implementation. The Python module is mainly for ease of porting code from other languages that use it, rather than for use in new code. -
Stephen Berndt over 8 yearsThis is exactly what I was looking for. Thank You!