30

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?

3
  • 1
    sys.argv is not a package. You'd use argparse. Commented Feb 12, 2016 at 14:44
  • 1
    sys.argv is a list of arguments. argparse is a package to help you deal with arguments (including adding a --help argument). Commented Feb 12, 2016 at 14:49
  • 2
    sys.argv is the list of strings derived from the commandline. argparse lets you create a parser the can decode sys.argv. For simple cases you can use sys.argv directly. Commented Feb 12, 2016 at 14:50

2 Answers 2

42

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I'm curious, is getopt the same getopt from perl's module?
@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.
This is exactly what I was looking for. Thank You!
optparse is now deprecated. It's better to use argparse.
7

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.