How to read/process command line arguments?

700,206

Solution 1

The canonical solution in the standard library is argparse (docs):

Here is an example:

from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument("-f", "--file", dest="filename",
                    help="write report to FILE", metavar="FILE")
parser.add_argument("-q", "--quiet",
                    action="store_false", dest="verbose", default=True,
                    help="don't print status messages to stdout")

args = parser.parse_args()

argparse supports (among other things):

  • Multiple options in any order.
  • Short and long options.
  • Default values.
  • Generation of a usage help message.

Solution 2

import sys

print("\n".join(sys.argv))

sys.argv is a list that contains all the arguments passed to the script on the command line. sys.argv[0] is the script name.

Basically,

import sys
print(sys.argv[1:])

Solution 3

Just going around evangelizing for argparse which is better for these reasons.. essentially:

(copied from the link)

  • argparse module can handle positional and optional arguments, while optparse can handle only optional arguments

  • argparse isn’t dogmatic about what your command line interface should look like - options like -file or /file are supported, as are required options. Optparse refuses to support these features, preferring purity over practicality

  • argparse produces more informative usage messages, including command-line usage determined from your arguments, and help messages for both positional and optional arguments. The optparse module requires you to write your own usage string, and has no way to display help for positional arguments.

  • argparse supports action that consume a variable number of command-line args, while optparse requires that the exact number of arguments (e.g. 1, 2, or 3) be known in advance

  • argparse supports parsers that dispatch to sub-commands, while optparse requires setting allow_interspersed_args and doing the parser dispatch manually

And my personal favorite:

  • argparse allows the type and action parameters to add_argument() to be specified with simple callables, while optparse requires hacking class attributes like STORE_ACTIONS or CHECK_METHODS to get proper argument checking

Solution 4

There is also argparse stdlib module (an "impovement" on stdlib's optparse module). Example from the introduction to argparse:

# script.py
import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'integers', metavar='int', type=int, choices=range(10),
         nargs='+', help='an integer in the range 0..9')
    parser.add_argument(
        '--sum', dest='accumulate', action='store_const', const=sum,
        default=max, help='sum the integers (default: find the max)')

    args = parser.parse_args()
    print(args.accumulate(args.integers))

Usage:

$ script.py 1 2 3 4
4

$ script.py --sum 1 2 3 4
10

Solution 5

If you need something fast and not very flexible

main.py:

import sys

first_name = sys.argv[1]
last_name = sys.argv[2]
print("Hello " + first_name + " " + last_name)

Then run python main.py James Smith

to produce the following output:

Hello James Smith

Share:
700,206
Admin
Author by

Admin

Updated on March 10, 2021

Comments

  • Admin
    Admin about 3 years
  • Admin
    Admin almost 15 years
    Are these built in modules the best? Or can you think of a better custom way?
  • Barry Wark
    Barry Wark almost 15 years
    Yes, these are the best. Since they're part of the standard library, you can be sure they'll be available and they're easy to use. optparse in particular is powerful and easy.
  • user1066101
    user1066101 almost 15 years
    @edgerA: What does "better custom way" mean?
  • jemfinch
    jemfinch about 14 years
    optparse is one of the best; getopt is old and really ought to be considered deprecated.
  • jpswain
    jpswain over 13 years
    This is now part of standard Python as of 2.7 and 3.2 :)
  • Xiong Chiamiov
    Xiong Chiamiov over 13 years
    For really simple stuff, this is the way to go, although you probably only want to use sys.argv[1:] (avoids the script name).
  • Roberto Bonvallet
    Roberto Bonvallet over 12 years
    There is already another command-line parsing module named Commando: github.com/lakshmivyas/commando. It wraps argparse by using decorators.
  • oob
    oob over 12 years
    at this point (12/2011), argparse is now considered a better option than optparse, correct?
  • earthmeLon
    earthmeLon almost 12 years
    Python Documentation suggests the use of argparse instead of optparse.
  • ArtOfWarfare
    ArtOfWarfare over 9 years
    What are "optional arguments"? You say they're in optparse. I thought that they were arguments that may or may not be provided, but you said they're in optparse while going on to say that "optparse requires that the exact number of arguments be known in advance". So either your definition of "optional argument" differs from what I thought, or your answer is inconsistent with itself.
  • gvoysey
    gvoysey about 8 years
    This has rapidly become my favorite way to go. It's string parsing so it's kind of brittle, but it's brittle all in one place and you can preview your logic at try.docopt.org . Optional and mutually-exclusive arguments are done in a really elegant way.
  • osman
    osman about 7 years
    Just a gripe: argparse documentation is also insanely, insanely complicated. You can't get a simple answer for "how do I make a command line argument take in a single value, and how do I access that value." </gripe>
  • John Lawrence Aspden
    John Lawrence Aspden almost 7 years
    I am desperate to see the rest of the code for naval_fate.py
  • lifebalance
    lifebalance almost 7 years
    @osman This gentle tutorial on argparse might help...
  • Juanjo Salvador
    Juanjo Salvador almost 7 years
    This is the best solution. Using argh is easier than another libs or using sys.
  • tripleee
    tripleee over 6 years
    A more realistic usage would be python main.py "James Smith" which puts James Smith in sys.argv[1] and produces an IndexError when you try to use the nonexistent sys.argv[2]. Quoting behavior will somewhat depend on which platform and shell you run Python from.
  • tripleee
    tripleee over 6 years
    I wanted to like argh but it's not particularly suitable for scenarios where your utmost desire is not to have a command with subcommands.
  • Kent Munthe Caspersen
    Kent Munthe Caspersen over 6 years
    I don't agree that my usage is less realistic. Pretend your program needs to know the exact first and last name of a person to run the script in a business where people can have multiple first and last names? If James Smith has Joseph as an extra first or last name, how would distinguish between whether Joseph is an extra first or last name if you only do python main.py "James Joseph Smith"? If you are concerned with index out of bounds, you can add a check for the number of provided arguments. Less realistic or not, my example shows how to handle multiple arguments.
  • circular-ruin
    circular-ruin about 6 years
    @tripleee YMMV, but I found that this was more of a defect in the documentation than in the library itself. It seems perfectly feasible to have def frobnicate_spleches(...) defining a function that does whatever your script does, then doing if __name__ == '__main__': argh.dispatch_command(frobnicate_spleches) at the end of the file.
  • Derek
    Derek about 6 years
    python and wheel re-invention
  • wim
    wim almost 6 years
    Since optparse is deprecated, the asker of the question is no longer a member on stack overflow, and this is the accepted answer on a highly visible question - please consider completely rewriting your example code to use stdlib argparse instead.
  • blitu12345
    blitu12345 almost 6 years
    its just a copy and paste
  • jfs
    jfs almost 6 years
    @blitu12345 at the time of the publication of my answer there were no other answers that mention argparse in any way. The module itself was not in stdlib¶ What do you have against code examples from the documentation? Why do you think it is necessary to come up with your own examples instead of examples provided by the author of the module? And I don't like link-only answers (I'm not alone).
  • blitu12345
    blitu12345 almost 6 years
    Peoples coming here already had an idea whats in the documentation and will be here only for further clearance about the topic.Same was my case but what i really found here is a copy and paste from the original docs.Peace!
  • mtraceur
    mtraceur almost 6 years
    @ArtOfWarfare "optional arguments" in this context presumably means arguments specified with option-like arguments such as -f or --foo, while "exact number of arguments be known in advance" presumably means positional arguments given without any preceding option flags.
  • sjas
    sjas over 5 years
    "Peoples coming here already had an idea whats in the documentation" - i highly doubt that assumtion. somehow.
  • WinEunuuchs2Unix
    WinEunuuchs2Unix almost 5 years
    All the other answers are for plotting a lunar landing mission. I'm just simply using gmail-trash-msg.py MessageID. This answer is straight forward to test MessageID parameter has been passed in sys.argv[1].
  • r.mirzojonov
    r.mirzojonov over 4 years
    @AymanHourieh you did not show how to get those arguments. The documentation of this module is a mess.