Python sys.argv[1] 在脚本中的含义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4117530/
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
sys.argv[1] meaning in script
提问by Switchkick
I'm currently teaching myself Python and was just wondering (In reference to my example below) in simplified terms what the sys.argv[1]represents. Is it simply asking for an input?
我目前正在自学 Python,只是想知道(参考我下面的示例)用简化的术语sys.argv[1]表示什么。它只是要求输入吗?
#!/usr/bin/python3.1
# import modules used here -- sys is a very standard one
import sys
# Gather our code in a main() function
def main():
print ('Hello there', sys.argv[1])
# Command line args are in sys.argv[1], sys.argv[2] ..
# sys.argv[0] is the script name itself and can be ignored
# Standard boilerplate to call the main() function to begin
# the program.
if __name__ == '__main__':
main()
采纳答案by Jason R. Coombs
I would like to note that previous answers made many assumptions about the user's knowledge. This answer attempts to answer the question at a more tutorial level.
我想指出,以前的答案对用户的知识做了很多假设。这个答案试图在更教程的层面上回答这个问题。
For every invocation of Python, sys.argvis automatically a list of strings representing the arguments (as separated by spaces) on the command-line. The name comes from the C programming conventionin which argv and argc represent the command line arguments.
对于 Python 的每次调用,sys.argv都会自动生成一个字符串列表,表示命令行上的参数(以空格分隔)。该名称来自C 编程约定,其中 argv 和 argc 表示命令行参数。
You'll want to learn more about lists and strings as you're familiarizing yourself with Python, but in the meantime, here are a few things to know.
当您熟悉 Python 时,您会想要了解更多关于列表和字符串的知识,但与此同时,这里有一些事情需要了解。
You can simply create a script that prints the arguments as they're represented. It also prints the number of arguments, using the lenfunction on the list.
您可以简单地创建一个脚本来打印所表示的参数。它还使用len列表中的函数打印参数的数量。
from __future__ import print_function
import sys
print(sys.argv, len(sys.argv))
The script requires Python 2.6 or later. If you call this script print_args.py, you can invoke it with different arguments to see what happens.
该脚本需要 Python 2.6 或更高版本。如果你调用这个脚本print_args.py,你可以用不同的参数调用它,看看会发生什么。
> python print_args.py
['print_args.py'] 1
> python print_args.py foo and bar
['print_args.py', 'foo', 'and', 'bar'] 4
> python print_args.py "foo and bar"
['print_args.py', 'foo and bar'] 2
> python print_args.py "foo and bar" and baz
['print_args.py', 'foo and bar', 'and', 'baz'] 4
As you can see, the command-line arguments include the script name but not the interpreter name. In this sense, Python treats the script asthe executable. If you need to know the name of the executable (python in this case), you can use sys.executable.
如您所见,命令行参数包括脚本名称但不包括解释器名称。从这个意义上说,Python 将脚本视为可执行文件。如果您需要知道可执行文件的名称(在本例中为 python),您可以使用sys.executable.
You can see from the examples that it is possible to receive arguments that do contain spaces if the user invoked the script with arguments encapsulated in quotes, so what you get is the list of arguments as supplied by the user.
您可以从示例中看到,如果用户调用脚本时将参数封装在引号中,则可能会收到包含空格的参数,因此您得到的是用户提供的参数列表。
Now in your Python code, you can use this list of strings as input to your program. Since lists are indexed by zero-based integers, you can get the individual items using the list[0] syntax. For example, to get the script name:
现在,在您的 Python 代码中,您可以使用此字符串列表作为程序的输入。由于列表由从零开始的整数索引,您可以使用 list[0] 语法获取单个项目。例如,要获取脚本名称:
script_name = sys.argv[0] # this will always work.
Although interesting, you rarely need to know your script name. To get the first argument after the script for a filename, you could do the following:
尽管很有趣,但您很少需要知道您的脚本名称。要获取文件名脚本后的第一个参数,您可以执行以下操作:
filename = sys.argv[1]
This is a very common usage, but note that it will fail with an IndexError if no argument was supplied.
这是一个非常常见的用法,但请注意,如果没有提供参数,它将失败并显示 IndexError。
Also, Python lets you reference a slice of a list, so to get another listof just the user-supplied arguments (but without the script name), you can do
此外,Python 允许您引用列表的一部分,因此要获取仅包含用户提供的参数的另一个列表(但没有脚本名称),您可以执行以下操作
user_args = sys.argv[1:] # get everything after the script name
Additionally, Python allows you to assign a sequence of items (including lists) to variable names. So if you expect the user to always supply two arguments, you can assign those arguments (as strings) to two variables:
此外,Python 允许您将一系列项目(包括列表)分配给变量名称。因此,如果您希望用户始终提供两个参数,则可以将这些参数(作为字符串)分配给两个变量:
user_args = sys.argv[1:]
fun, games = user_args # len(user_args) had better be 2
So, to answer your specific question, sys.argv[1]represents the first command-line argument (as a string) supplied to the script in question. It will not prompt for input, but it will fail with an IndexError if no arguments are supplied on the command-line following the script name.
因此,为了回答您的具体问题,sys.argv[1]表示string提供给相关脚本的第一个命令行参数(作为 a )。它不会提示输入,但如果在脚本名称后面的命令行上没有提供参数,它将失败并显示 IndexError。
回答by Frédéric Hamidi
sys.argv[1]contains the first command lineargumentpassed to your script.
sys.argv[1]包含传递给脚本的第一个命令行参数。
For example, if your script is named hello.pyand you issue:
例如,如果您的脚本已命名hello.py并且您发出:
$ python3.1 hello.py foo
or:
或者:
$ chmod +x hello.py # make script executable
$ ./hello.py foo
Your script will print:
您的脚本将打印:
Hello there foo
回答by TartanLlama
sys.argv is a list containing the script path and command line arguments; i.e. sys.argv[0] is the path of the script you're running and all following members are arguments.
sys.argv 是一个包含脚本路径和命令行参数的列表;即 sys.argv[0] 是您正在运行的脚本的路径,所有以下成员都是参数。
回答by CodeWombat
Just adding to Frederic's answer, for example if you call your script as follows:
只需添加 Frederic 的答案,例如,如果您按如下方式调用脚本:
./myscript.py foo bar
./myscript.py foo bar
sys.argv[0]would be "./myscript.py"
sys.argv[1]would be "foo" and
sys.argv[2]would be "bar" ... and so forth.
sys.argv[0]会是“./myscript.py”
sys.argv[1]会是“foo”,
sys.argv[2]会是“bar”......等等。
In your example code, if you call the script as follows ./myscript.py foo , the script's output will be "Hello there foo".
在您的示例代码中,如果您按如下方式调用脚本./myscript.py foo ,则脚本的输出将是“Hello there foo”。
回答by user2205939
sys.argvis a list.
sys.argv是一个列表。
This list is created by your command line, it's a list of your command line arguments.
此列表由您的命令行创建,它是您的命令行参数列表。
For example:
例如:
in your command line you input something like this,
在你的命令行你输入这样的东西,
python3.2 file.py something
sys.argvwill become a list ['file.py', 'something']
sys.argv将成为一个列表 ['file.py', 'something']
In this case sys.argv[1] = 'something'
在这种情况下 sys.argv[1] = 'something'
回答by Rahul
Adding a few more points to Jason's Answer :
在 Jason 的回答中再补充几点:
For taking all user provided arguments : user_args = sys.argv[1:]
获取所有用户提供的参数: user_args = sys.argv[1:]
Consider the sys.argv as a list of strings as (mentioned by Jason). So all the list manipulations will apply here. This is called "List Slicing". For more info visit here.
将 sys.argv 视为字符串列表(由 Jason 提到)。因此,所有列表操作都将适用于此。这称为“列表切片”。欲了解更多信息,请访问这里。
The syntax is like this : list[start:end:step]. If you omit start, it will default to 0, and if you omit end, it will default to length of list.
语法是这样的:list[start:end:step]。如果省略 start,则默认为 0,如果省略 end,则默认为列表长度。
Suppose you only want to take all the arguments after 3rd argument, then :
假设您只想获取第 3 个参数之后的所有参数,则:
user_args = sys.argv[3:]
Suppose you only want the first two arguments, then :
假设您只想要前两个参数,然后:
user_args = sys.argv[0:2] or user_args = sys.argv[:2]
Suppose you want arguments 2 to 4 :
假设您想要参数 2 到 4 :
user_args = sys.argv[2:4]
Suppose you want the last argument (last argument is always -1, so what is happening here is we start the count from back. So start is last, no end, no step) :
假设你想要最后一个参数(最后一个参数总是 -1,所以这里发生的是我们从后面开始计数。所以开始是最后一个,没有结束,没有步骤):
user_args = sys.argv[-1]
Suppose you want the second last argument :
假设您想要倒数第二个参数:
user_args = sys.argv[-2]
Suppose you want the last two arguments :
假设您想要最后两个参数:
user_args = sys.argv[-2:]
Suppose you want the last two arguments. Here, start is -2, that is second last item and then to the end (denoted by ":") :
假设您想要最后两个参数。在这里,开始是 -2,即倒数第二个项目,然后到结尾(用“:”表示):
user_args = sys.argv[-2:]
Suppose you want the everything except last two arguments. Here, start is 0 (by default), and end is second last item :
假设您想要除最后两个参数之外的所有内容。这里,start 是 0(默认),end 是倒数第二项:
user_args = sys.argv[:-2]
Suppose you want the arguments in reverse order :
假设您想要倒序的参数:
user_args = sys.argv[::-1]
Hope this helps.
希望这可以帮助。
回答by JBJ
To pass arguments to your python script while running a script via command line
在通过命令行运行脚本时将参数传递给 python 脚本
python create_thumbnail.py test1.jpg test2.jpg
python create_thumbnail.py test1.jpg test2.jpg
here, script name - create_thumbnail.py, argument 1 - test1.jpg, argument 2 - test2.jpg
这里,脚本名称 - create_thumbnail.py,参数 1 - test1.jpg,参数 2 - test2.jpg
With in the create_thumbnail.py script i use
在 create_thumbnail.py 脚本中,我使用
sys.argv[1:]
which give me the list of arguments i passed in command line as ['test1.jpg', 'test2.jpg']
这给了我我在命令行中作为 ['test1.jpg', 'test2.jpg'] 传递的参数列表
回答by geekidharsh
sys.argv will display the command line args passed when running a script or you can say sys.argv will store the command line arguments passed in python while running from terminal.
sys.argv 将显示运行脚本时传递的命令行参数,或者您可以说 sys.argv 将存储从终端运行时在 python 中传递的命令行参数。
Just try this:
试试这个:
import sys
print sys.argv
argv stores all the arguments passed in a python list. The above will print all arguments passed will running the script.
argv 存储在 python 列表中传递的所有参数。以上将打印所有传递的参数将运行脚本。
Now try this running your filename.py like this:
现在试试这个运行你的 filename.py 像这样:
python filename.py example example1
this will print 3 arguments in a list.
这将在列表中打印 3 个参数。
sys.argv[0] #is the first argument passed, which is basically the filename.
Similarly, argv1is the first argument passed, in this case 'example'
类似地,argv 1是传递的第一个参数,在本例中为 'example'
A similar question has been asked already herebtw. Hope this helps!
顺便说一句,这里已经提出了类似的问题。希望这可以帮助!
回答by Jaidee
sys.argvis a attribute of the sysmodule. It says the arguments passed into the file in the command line. sys.argv[0]catches the directory where the file is located. sys.argv[1]returns the first argument passed in the command line. Think like we have a example.py file.
sys.argv是sys模块的一个属性。它表示在命令行中传递到文件中的参数。sys.argv[0]捕获文件所在的目录。sys.argv[1]返回在命令行中传递的第一个参数。想想我们有一个 example.py 文件。
example.py
例子.py
import sys # Importing the main sys module to catch the arguments
print(sys.argv[1]) # Printing the first argument
Now here in the command prompt when we do this:
现在,当我们执行此操作时,在命令提示符处:
python example.py
It will throw a index error at line 2. Cause there is no argument passed yet. You can see the length of the arguments passed by user using if len(sys.argv) >= 1: # Code.
If we run the example.py with passing a argument
它会在第 2 行抛出一个索引错误。因为还没有传递参数。您可以使用if len(sys.argv) >= 1: # Code. 如果我们运行example.py并传递一个参数
python example.py args
It prints:
它打印:
args
Because it was the first arguement! Let's say we have made it a executable file using PyInstaller. We would do this:
因为这是第一次争吵!假设我们已经使用 PyInstaller 将它变成了一个可执行文件。我们会这样做:
example argumentpassed
It prints:
它打印:
argumentpassed
It's really helpful when you are making a command in the terminal. First check the length of the arguments. If no arguments passed, do the help text.
当您在终端中发出命令时,这真的很有帮助。首先检查参数的长度。如果没有传递参数,请执行帮助文本。

