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'>
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:
Python argparse command line flags without arguments
(5 answers)
Closed 4 years ago.
I want to use argparse to get option to my program. Here is my sample program:
from argparse import ArgumentParser
parser = ArgumentParser()
print("enter the numbers:")
a=int(input("number 1:"))
b=int(input("number 2:"))
parser.add_argument('-a','--add')
parser.add_argument('-s','--sub')
options = parser.parse_args()
if options:
c=a+b
if options.d:
c=a-b
print(c)
it gives the output correctly if I use
python file.pu -a 1
But I don't want to give value like 1 in compilation. What I want is
python file.py -a
that performs addition.
python file.py -s
that performs subtraction.
How to change the code for it?
You can use:
action='store_true'
...in the following:
parser.add_argument('-a', '-add', action='store_true')
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:
Can't get argparse to read quoted string with dashes in it?
(7 answers)
Closed 5 years ago.
I'm doing a command line utility that can receive a parameter starting with a minus or plus, for instance, -gtest or +gtest the problem is that python3 don't accept this:
This is a minimal code that reproduce this problem:
import argparse
if (__name__== "__main__"):
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--string', action='store',
help='String value')
p = parser.parse_args()
if p.string:
print("pass value:", p.string)
I try to invoke it as:
./example.py -s -gtest
./example.py -s "-gtest"
./example.py -s \-gtest
And always get next error:
usage: example.py [-h] [-s STRING]
example.py: error: argument -s/--string: expected one argument
So, my question is how I can pass a argument starting with a minus using argparse
You can run it with:
python example.py -s-gtest
python example.py -s+gtest
So simply not putting any space, nor escaping it in any special way.
This question already has answers here:
How to read/process command line arguments?
(22 answers)
Closed 8 years ago.
For example I have function that takes --config argument from command line.
So to launch it from console I have to enter following:
>>> my_function --config
I want to create file like new_func.py and launch my_function --config from here.
How can I do this?
Use argparse module:
import argparse
parser = argparse.ArgumentParser(description='Command line exemple.')
parser.add_argument('--config', dest='fileconf', action='store',
help='my argument description)')
args = parser.parse_args()
print args.fileconf # do something with fileconf value