pythoncmdcommand-line-arguments

Pass arguments from cmd to python script


I write my scripts in python and run them with cmd by typing in:

C:\> python script.py

Some of my scripts contain separate algorithms and methods which are called based on a flag. Now I would like to pass the flag through cmd directly rather than having to go into the script and change the flag prior to run, I want something similar to:

C:\> python script.py -algorithm=2

I have read that people use sys.argv for almost similar purposes however reading the manuals and forums I couldn't understand how it works.


Solution

  • There are a few modules specialized in parsing command line arguments: getopt, optparse and argparse. optparse is deprecated, and getopt is less powerful than argparse, so I advise you to use the latter, it'll be more helpful in the long run.

    Here's a short example:

    import argparse
    
    # Define the parser
    parser = argparse.ArgumentParser(description='Short sample app')
    
    # Declare an argument (`--algo`), saying that the 
    # corresponding value should be stored in the `algo` 
    # field, and using a default value if the argument 
    # isn't given
    parser.add_argument('--algo', action="store", dest='algo', default=0)
    
    # Now, parse the command line arguments and store the 
    # values in the `args` variable
    args = parser.parse_args()
    
    # Individual arguments can be accessed as attributes...
    print args.algo
    

    That should get you started. At worst, there's plenty of documentation available on line (say, this one for example)...