This question already has answers here:
How to read/process command line arguments?
(22 answers)
Closed 4 years ago.
I have a file.py that I want to pass base_url to when called, so that base_url variable value can be dynamic upon running python file.py base_url='http://google.com' the value of http://google.com could then be used directly in the execution of file.py.
How might I go about doing this?
Thanks
The command line arguments are stored in the list sys.argv. sys.argv[0] is the name of the command that was invoked.
import sys
if len(sys.argv) != 2:
sys.stderr.write("usage: {} base_url".format(sys.argv[0]))
exit(-1) # or deal with this case in another way
base_url_arg = sys.argv[1]
Depending on the input format, base_url_arg might have to be further processed.
sys.argv.
How to use sys.argv in Python
For parsing arguments passed as "name=value" strings, you can do something like:
import sys
args = {}
for pair in sys.argv[1:]:
args.__setitem__(*((pair.split('=', 1) + [''])[:2]))
# access args['base_url'] here
and if you want more elaborate parsing of command line options, use argparse.
Here's a tutorial on argparse.
Related
This question already has answers here:
How to read/process command line arguments?
(22 answers)
Closed 4 years ago.
I have a file.py that I want to pass base_url to when called, so that base_url variable value can be dynamic upon running python file.py base_url='http://google.com' the value of http://google.com could then be used directly in the execution of file.py.
How might I go about doing this?
Thanks
The command line arguments are stored in the list sys.argv. sys.argv[0] is the name of the command that was invoked.
import sys
if len(sys.argv) != 2:
sys.stderr.write("usage: {} base_url".format(sys.argv[0]))
exit(-1) # or deal with this case in another way
base_url_arg = sys.argv[1]
Depending on the input format, base_url_arg might have to be further processed.
sys.argv.
How to use sys.argv in Python
For parsing arguments passed as "name=value" strings, you can do something like:
import sys
args = {}
for pair in sys.argv[1:]:
args.__setitem__(*((pair.split('=', 1) + [''])[:2]))
# access args['base_url'] here
and if you want more elaborate parsing of command line options, use argparse.
Here's a tutorial on argparse.
This question already has answers here:
How to read/process command line arguments?
(22 answers)
Closed 2 years ago.
I've been doing some exercises for AI course and I to get arguments to my code directly from the command line, for example python solution.py resolution_examples/small_example.txt. I now in java you can pass arguments to main fun via command line, but can you do the same thing in python?
sys module has attribute argv which contains all command line parameters.
import sys
print(sys.argv)
For fast handling, that should be enough but when you need a bit more control over cli parsing, standard library has lib called argparse: https://docs.python.org/3/library/argparse.html
Try:
import sys
print(sys.argv)
This question already has answers here:
Passing a tuple as command line argument
(3 answers)
Closed 2 years ago.
Have a question,
I'm writing a python-script and need to pass argument to the script from cmd.
My code to implement this little feature:
import sys
cars = sys.argv[1]
From command line, I type the next command:
python my_script.py ("Opel", "Nissan", 'Reno')
But when I checked the results, it was not a tuple, it was a string. How can I get a tuple from argument?
The command line does not know about Python data structures. All you get from there are strings. You can create them in Python, however:
cars = sys.argv[1].split()
# cars = tuple(sys.argv[1].split())
and call script as
python my_script.py "Opel Nissan Reno"
For more advanced argument processing, you should consider using the argparse module.
command line is not define tuple.
try this from command line
python my_script.py "Opel" "Nissan" "Reno"
import sys
# get from 1 to end
cars = sys.argv[1:]
How about this:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--data', nargs='+', type=str)
args = parser.parse_args()
my_tuple = tuple(args.data)
print(type(my_tuple)) # Check type
Run:
python my_script.py --data Opel Nissan Reno
Output:
<class 'tuple'>
This question already has answers here:
How to read/process command line arguments?
(22 answers)
Closed 2 years ago.
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.
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)...
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])
Try using the getopt module. It can handle both short and long command line options and is implemented in a similar way in other languages (C, shell scripting, etc):
import sys, getopt
def main(argv):
# default algorithm:
algorithm = 1
# parse command line options:
try:
opts, args = getopt.getopt(argv,"a:",["algorithm="])
except getopt.GetoptError:
<print usage>
sys.exit(2)
for opt, arg in opts:
if opt in ("-a", "--algorithm"):
# use alternative algorithm:
algorithm = arg
print "Using algorithm: ", algorithm
# Positional command line arguments (i.e. non optional ones) are
# still available via 'args':
print "Positional args: ", args
if __name__ == "__main__":
main(sys.argv[1:])
You can then pass specify a different algorithm by using the -a or --algorithm= options:
python <scriptname> -a2 # use algorithm 2
python <scriptname> --algorithm=2 # ditto
See: getopt documentation
This question already has answers here:
How to read/process command line arguments?
(22 answers)
Closed last month.
What would be an easy expression to process command line arguments if I'm expecting anything like 001 or 999 (let's limit expectations to 001...999 range for this time), and few other arguments passed, and would like to ignore any unexpected?
I understand if for example I need to find out if "debug" was passed among parameters it'll be something like that:
if 'debug' in argv[1:]:
print 'Will be running in debug mode.'
How to find out if 009 or 575 was passed?
All those are expected calls:
python script.py
python script.py 011
python script.py 256 debug
python script.py 391 xls
python script.py 999 debug pdf
At this point I don't care about calls like that:
python script.py 001 002 245 568
python script.py some unexpected argument
python script.py 0001
python script.py 02
...first one - because of more than one "numeric" argument; second - because of... well, unexpected arguments; third and fourth - because of non-3-digits arguments.
As others answered, optparse is the best option, but if you just want quick code try something like this:
import sys, re
first_re = re.compile(r'^\d{3}$')
if len(sys.argv) > 1:
if first_re.match(sys.argv[1]):
print "Primary argument is : ", sys.argv[1]
else:
raise ValueError("First argument should be ...")
args = sys.argv[2:]
else:
args = ()
# ... anywhere in code ...
if 'debug' in args:
print 'debug flag'
if 'xls' in args:
print 'xls flag'
EDIT: Here's an optparse example because so many people are answering optparse without really explaining why, or explaining what you have to change to make it work.
The primary reason to use optparse is it gives you more flexibility for expansion later, and gives you more flexibility on the command line. In other words, your options can appear in any order and usage messages are generated automatically. However to make it work with optparse you need to change your specifications to put '-' or '--' in front of the optional arguments and you need to allow all the arguments to be in any order.
So here's an example using optparse:
import sys, re, optparse
first_re = re.compile(r'^\d{3}$')
parser = optparse.OptionParser()
parser.set_defaults(debug=False,xls=False)
parser.add_option('--debug', action='store_true', dest='debug')
parser.add_option('--xls', action='store_true', dest='xls')
(options, args) = parser.parse_args()
if len(args) == 1:
if first_re.match(args[0]):
print "Primary argument is : ", args[0]
else:
raise ValueError("First argument should be ...")
elif len(args) > 1:
raise ValueError("Too many command line arguments")
if options.debug:
print 'debug flag'
if options.xls:
print 'xls flag'
The differences here with optparse and your spec is that now you can have command lines like:
python script.py --debug --xls 001
and you can easily add new options by calling parser.add_option()
Have a look at the optparse module. Dealing with sys.argv yourself is fine for really simple stuff, but it gets out of hand quickly.
Note that you may find optparse easier to use if you can change your argument format a little; e.g. replace debug with --debug and xls with --xls or --output=xls.
optparse is your best friend for parsing the command line. Also look into argparse; it's not in the standard library, though.
If you want to implement actual command line switches, give getopt a look. It's incredibly simple to use, too.
Van Gale is largely correct in using the regular expression against the argument. However, it is NOT absolutely necessary to make everything an option when using optparse, which splits sys.argv into options and arguments, based on whether a "-" or "--" is in front or not. Some example code to go through just the arguments:
import sys
import optparse
claParser = optparse.OptionParser()
claParser.add_option(
(opts, args) = claParser.parse_args()
if (len(args) >= 1):
print "Arguments:"
for arg in args:
print " " + arg
else:
print "No arguments"
sys.exit(0)
Yes, the args array is parsed much the same way as sys.argv would be, but the ability to easily add options if needed has been added. For more about optparse, check out the relevant Python doc.