如何在Python中访问命令行参数?

问题:如何在Python中访问命令行参数?

我使用python创建我的项目设置设置,但我需要获取命令行参数的帮助。

我在终端上尝试了这个:

$python myfile.py var1 var2 var3

在我的Python文件中,我想使用所有输入的变量。

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.


回答 0

Python教程对此进行了解释

import sys

print(sys.argv)

更具体地说,如果您运行python example.py one two three

>>> import sys
>>> print(sys.argv)
['example.py', 'one', 'two', 'three']

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

回答 1

import sys

sys.argv[1:]

将为您提供参数列表(不包括python文件的名称)

import sys

sys.argv[1:]

will give you a list of arguments (not including the name of the python file)


回答 2

我强烈建议argparsePython 2.7及更高版本随附。

argparse模块减少了样板代码,并使您的代码更健壮,因为该模块可以处理所有标准用例(包括子命令),为您生成帮助和用法,检查并清理用户输入-您在使用时需要担心的所有事情正在使用sys.argv方法。它是免费的(内置)。

这里有个小例子:

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)

和输出为 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

python prog.py 1您所期望的:

2

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 for python prog.py 1 as you would expect:

2

回答 3

Python代码:

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

调用:

$python myfile.py var1 var2 var3

输出:

Params= var1 var2 var3 

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 

回答 4

您可以使用 sys.argv用来获取参数列表。

如果您需要访问各个元素,则可以使用

sys.argv[i]  

i索引在哪里,0将为您提供正在执行的python文件名。之后的任何索引都是传递的参数。

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.


回答 5

如果您这样称呼它: $ python myfile.py var1 var2 var3

import sys

var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]

与数组类似,您也拥有sys.argv[0]始终是当前工作目录的数组。

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.


回答 6

我可以想到的一些其他事项。

正如@allsyed所说,sys.argv提供了一个组件列表(包括程序名称),因此,如果您想知道通过命令行传递的元素数量,可以使用len()来确定它。基于此,如果用户未传递特定数量的参数,则可以设计异常/错误消息。

另外,如果您正在寻找一种更好的方式来处理命令行参数,我建议您查看https://docs.python.org/2/howto/argparse.html

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