Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass arguments from cmd to python script [duplicate]

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.

like image 555
Kevin Bell Avatar asked May 23 '13 11:05

Kevin Bell


People also ask

How can you pass command line arguments to a script?

Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.

How do you store command line arguments in Python?

To access command-line arguments from within a Python program, first import the sys package. You can then refer to the full set of command-line arguments, including the function name itself, by referring to a list named argv. In either case, argv refers to a list of command-line arguments, all stored as strings.


2 Answers

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)...

like image 133
Pierre GM Avatar answered Sep 22 '22 05:09

Pierre GM


It might not answer your question, but some people might find it usefull (I was looking for this here):

How to send 2 args (arg1 + arg2) from cmd to python 3:

----- Send the args in test.cmd:

python "C:\Users\test.pyw" "arg1" "arg2"

----- Retrieve the args in test.py:

print ("This is the name of the script= ", sys.argv[0])
print("Number of arguments= ", len(sys.argv))
print("all args= ", str(sys.argv))
print("arg1= ", sys.argv[1])
print("arg2= ", sys.argv[2])
like image 36
JinSnow Avatar answered Sep 23 '22 05:09

JinSnow