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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4033723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:56:09  来源:igfitidea点击:

How do I access command line arguments in Python?

pythoncommand-line

提问by ParisNakitaKejser

I use python to create my project settings setup, but I need help getting the command line arguments.

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

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 文件中,我想使用所有输入的变量。

采纳答案by SilentGhost

Python tutorial explains it:

Python教程解释了它

import sys

print(sys.argv)

More specifically, if you run python example.py one two three:

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

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

回答by Ryan M

import sys

sys.argv[1:]

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

会给你一个参数列表(不包括python文件的名称)

回答by allsyed

You can use sys.argvto get the arguments as a list.

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

If you need to access individual elements, you can use

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

sys.argv[i]  

where iis index, 0will give you the python filename being executed. Any index after that are the arguments passed.

i索引在哪里,0会给你正在执行的python文件名。之后的任何索引都是传递的参数。

回答by 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 

回答by lvadim01

If you call it like this: $ python myfile.py var1 var2 var3

如果你这样称呼它: $ 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]它始终是当前工作目录。

回答by Rohan Sadale

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.

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

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

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

回答by Michael Dorner

I highly recommend argparsewhich comes with Python 2.7 and later.

我强烈推荐argparsePython 2.7 及更高版本附带的。

The argparsemodule 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.argvapproach. And it is for free (built-in).

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

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

和输出 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 1as you would expect:

python prog.py 1你所期望的:

2