How do I access command line arguments?
I use python to create my project settings setup, but I need help getting the command line arguments.
I tried this on the terminal:
$python myfile.py开发者_开发百科 var1 var2 var3
In my Python file, I want to use all variables that are input.
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']
To get only the command line arguments
(not including the name of the Python file)
import sys
sys.argv[1:]
The [1:]
is a slice starting from the second element (index 1) and going to the end of the arguments list. This is because the first element is the name of the Python file, and we want to remove that.
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
Python code:
import sys
# main
param_1= sys.argv[1]
param_2= sys.argv[2]
param_3= sys.argv[3]
print 'Params=', param_1, param_2, param_3
Invocation:
$python myfile.py var1 var2 var3
Output:
Params= var1 var2 var3
You can use sys.argv
to get the arguments as a list.
If you need to access individual elements, you can use
sys.argv[i]
where i
is index, 0
will give you the python filename being executed. Any index after that are the arguments passed.
You can access arguments by key using "argparse".
Let's say that we have this command:
python main.py --product_id 1001028
To access the argument product_id, we need to declare it first and then get it:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--product_id', dest='product_id', type=str, help='Add product_id')
args = parser.parse_args()
print (args.product_id)
Output:
1001028
If you call it like this: $ python myfile.py var1 var2 var3
import sys
var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]
Similar to arrays you also have sys.argv[0]
which is always the current working directory.
Some additional things that I can think of.
As @allsyed said sys.argv gives a list of components (including program name), so if you want to know the number of elements passed through command line you can use len() to determine it. Based on this, you can design exception/error messages if user didn't pass specific number of parameters.
Also if you looking for a better way to handle command line arguments, I would suggest you look at https://docs.python.org/2/howto/argparse.html
First, You will need to import sys
sys - System-specific parameters and functions
This module provides access to certain variables used and maintained by the interpreter, and to functions that interact strongly with the interpreter. This module is still available. I will edit this post in case this module is not working anymore.
And then, you can print the numbers of arguments or what you want here, the list of arguments.
Follow the script below :
#!/usr/bin/python
import sys
print 'Number of arguments entered :' len(sys.argv)
print 'Your argument list :' str(sys.argv)
Then, run your python script :
$ python arguments_List.py chocolate milk hot_Chocolate
And you will have the result that you were asking :
Number of arguments entered : 4
Your argument list : ['arguments_List.py', 'chocolate', 'milk', 'hot_Chocolate']
Hope that helped someone.
Using the following code, you can check whether the arguments are entered. If it is the case, the arguments are printed; otherwise, a message stating that the arguments are not entered is printed.
import sys
if len(sys.args) <= 1:
print("the arguments are not entered in the command line")
else:
for arg in args:
print(arg)
should use of sys ( system ) module . the arguments has str type and are in an array
NOTICE : argv is not function or class and is variable & can change
NOTICE : argv[0] is file name
NOTICE : because python written in c , C have main(int argc , char *argv[]); but argc in sys module does not exits
NOTICE : sys module is named System and written in C that NOT A SOURCE BASED MODULE
from sys import argv # or
from sys import * # or
import sys
# code
print("is list") if type(sys.argv) == list else pass # is list ,or
print("is list") if type(argv) == list else pass # is list
# arguments are str ( string )
print(type(sys.argv[1])) # str
# command : python filename.py 1 2 3
print(len(sys.argv)) # 3
print(sys.argv[1],'\n',sys.argv[2]'\n',sys.argv[3]) # following
'''
1
2
3
'''
# command : python filename.py 123
print(len(sys.argv)) # 1
print(sys.argv[1]) # following
'''
123
'''
精彩评论