First (and probably most preferable) solution is to put the second and third argument in quotes as Susmit Agrawal suggested. Then the shell itself will split the command line into arguments appropriately.
python mytest.py [email protected] "value of file 1" "value of file 2"
In case you really need to pass arguments without quotes though, you will have to accept that the shell will be splitting your second and third argument at spaces, so you will need to reconstruct them from sys.argv yourself.
Lastly, you may want to explore argparse library to help you with parsing the command line arguments. In this case you may want to use optional arguments with nargs set to '+' or some certain number based on your command line API. For example, if you define and parse your arguments the following way,
parser = argparse.ArgumentParser()
parser.add_argument('--value-1', nargs=4)
parser.add_argument('--value-2', nargs=4)
parser.add_argument('email', nargs='+')
args = parser.parse_args()
print(args)
then you can call your Python program as
python mytest.py [email protected] --value-1 value of file 1 --value-2 value of file 2
And get the following result,
Namespace(email=['[email protected]'], value_1=['value', 'of', 'file', '1'], value_2=['value', 'of', 'file', '2'])
which you can then conveniently access as
print(args.value_1)
print(args.value_2)
print(args.email)
Answer from Victor on Stack OverflowFirst (and probably most preferable) solution is to put the second and third argument in quotes as Susmit Agrawal suggested. Then the shell itself will split the command line into arguments appropriately.
python mytest.py [email protected] "value of file 1" "value of file 2"
In case you really need to pass arguments without quotes though, you will have to accept that the shell will be splitting your second and third argument at spaces, so you will need to reconstruct them from sys.argv yourself.
Lastly, you may want to explore argparse library to help you with parsing the command line arguments. In this case you may want to use optional arguments with nargs set to '+' or some certain number based on your command line API. For example, if you define and parse your arguments the following way,
parser = argparse.ArgumentParser()
parser.add_argument('--value-1', nargs=4)
parser.add_argument('--value-2', nargs=4)
parser.add_argument('email', nargs='+')
args = parser.parse_args()
print(args)
then you can call your Python program as
python mytest.py [email protected] --value-1 value of file 1 --value-2 value of file 2
And get the following result,
Namespace(email=['[email protected]'], value_1=['value', 'of', 'file', '1'], value_2=['value', 'of', 'file', '2'])
which you can then conveniently access as
print(args.value_1)
print(args.value_2)
print(args.email)
you can use argparse to pass your argument:
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-stv1', type=str)
parser.add_argument('-stv2', type=str)
parser.add_argument('-email', nargs='+')
args = parser.parse_args()
print(args)
nargs='+' indicate that at least you should pass one argument as email or more.
Executing the script give the following :
python3 script.py -email [email protected] [email protected] -stv1 "value of file 1" -stv2 "value of file 2"
Namespace(email=['[email protected]', '[email protected]'], stv1='value of file 1', stv2='value of file 2')
How to pass multiple arguments in command line using python - Stack Overflow
Best way to pass a ton of command line arguments into a Python application?
list - Python pass multiple strings to a single command line argument - Stack Overflow
python - How do I access command line arguments? - Stack Overflow
Videos
I'm writing an application with a bunch of classes that interact with each other, and the client would like to be able to specify parameters through the command line. For example app num_people=1000 realtime=True outputdir='my/home/dir', but with far more options. The options will be in a variety of classes, and will have defaults if nothing is passed in.
What is the best way to do this in Python 3? I know about argparse but it seems like a potential framework I'll use to answer this question, not the actual solution.
You pass the nargs argument, not action="append":
parser.add_argument("infile", default=[], nargs='*')
* means zero or more, just like in regular expressions.
You can also use + if you require at least one. Since you have a default, I am assuming that the user is not required to pass any.
Your code, from what all you posted, looks solid.
The problem is with the snippet you posted thats supposed to traverse the list. The way your program is setup you cant use infile as a variable
All you need to do to fix it is switch infile with options.infile
Specifically:
for filename in options.infile:
print(filename)
The reason for this is all your arguments are stored in the options "Namespace"-type variable
Python tutorial explains it:
import sys
print(sys.argv)
More specifically, if you run python example.py one two three:
>>> import sys
>>> print(sys.argv)
['example.py', 'one', 'two', 'three']
I highly recommend argparse which comes with Python 2.7 and later.
The argparse module reduces boiler plate code and makes your code more robust, because the module handles all standard use cases (including subcommands), generates the help and usage for you, checks and sanitize the user input - all stuff you have to worry about when you are using sys.argv approach. And it is for free (built-in).
Here a small example:
import argparse
parser = argparse.ArgumentParser("simple_example")
parser.add_argument("counter", help="An integer will be increased by 1 and printed.", type=int)
args = parser.parse_args()
print(args.counter + 1)
and the output for python prog.py -h
usage: simple_example [-h] counter
positional arguments:
counter counter will be increased by 1 and printed.
optional arguments:
-h, --help show this help message and exit
and the output for python prog.py 1 As one would expect:
2
Command line arguments are passed as an array to the program, with the first being usually the program's location. So we skip argv[0] and move on to the other arguments.
This example doesn't include error checking.
from sys import argv
def operation(name, number):
...
contact_name = argv[1]
contact_no = argv[2]
operation(contact_name, contact_no)
Calling from command line:
python myscript.py John 5
You can use argparse to write user-friendly command-line interfaces.
import argparse
parser = argparse.ArgumentParser(description='You can add a description here')
parser.add_argument('-n', '--name', help='Your name', required=True)
args = parser.parse_args()
print args.name
To call the script use:
python script.py -n a_name
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:
import sys, getopt
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])