ChatGPT解决这个技术问题 Extra ChatGPT

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.


y
yiwei

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']

R
Ryan M

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.


What does [1:] mean?
@KolobCanyon it means "take a sublist starting from index 1 till the end", i.e. skip the first element
@KolobCanyon take the the second argument [1:] upwards because the first argument of sys.argv is by default the name of the python file that you are running for example testrun.py.
M
Michael Dorner

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

Quality answer, not really sure why anyone here would use any of the other approaches given here. Especially since it's built in! Don't you guys have better things to do than parsing?
Just to mention how you should access the specific argument in args namespace: args.counter
@Bassinator In cases when no parsing of arguments is needed.
to use default value, without specific value in the command line, you can use something like: parser.add_argument('var3', nargs='?', type=int, default=3) var3 is a optional param, if you don't specify a value in the command line you can access to var3 in your code, default value for var3=3
You are the boss! Thanks man!
C
Charles P.

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 

R
Rakete1111

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.


l
lvadim01

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.


sys.argv[0] is not the current working directory. It is the name of the file that is executing.
R
Rohan

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


M
Mohamad Hamouday

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

佚名

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.


佚名

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
'''