sys.argv [1]在脚本中的含义

时间:2021-12-04 23:02:57

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()

8 个解决方案

#1


227  

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.argv is automatically a list of strings representing the arguments (as separated by spaces) on the command-line. The name comes from the C programming convention in 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 it 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 len function 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 as the 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 that's interesting to know, 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 list of 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, in final answer to 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]表示提供给相关脚本的第一个命令行参数(作为字符串)。它不会提示输入,但如果在脚本名称后面的命令行中没有提供任何参数,它将失败并返回IndexError。

#2


28  

sys.argv[1] contains the first command line argument passed to your script.

sys.argv [1]包含传递给脚本的第一个命令行参数。

For example, if your script is named hello.py and 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

#3


14  

sys.argv is 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.argv will become a list ['file.py', 'something']

sys.argv将成为一个列表['file.py','something']

In this case sys.argv[1] = 'something'

在这种情况下,sys.argv [1] ='某事'

#4


11  

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”。

#5


6  

Adding a few more points to Jason's Answer :

再添加几点给杰森的答案:

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,则默认为list的长度。

Suppose you only want to take all the arguments after 3rd argument, then :

假设你只想在第三个参数之后获取所有参数,那么:

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 ":") :

假设你想要最后两个参数。这里,start是-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.

希望这可以帮助。

#6


3  

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]是您正在运行的脚本的路径,所有后续成员都是参数。

#7


2  

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

#8


0  

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将显示运行脚本时传递的命令行args,或者您可以说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, argv1 is the first argument passed, in this case 'example'

同样,argv1是传递的第一个参数,在本例中是'example'

A similar question has been asked already here btw. Hope this helps!

在这里已经有人问过类似的问题了。希望这可以帮助!

#1


227  

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.argv is automatically a list of strings representing the arguments (as separated by spaces) on the command-line. The name comes from the C programming convention in 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 it 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 len function 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 as the 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 that's interesting to know, 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 list of 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, in final answer to 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]表示提供给相关脚本的第一个命令行参数(作为字符串)。它不会提示输入,但如果在脚本名称后面的命令行中没有提供任何参数,它将失败并返回IndexError。

#2


28  

sys.argv[1] contains the first command line argument passed to your script.

sys.argv [1]包含传递给脚本的第一个命令行参数。

For example, if your script is named hello.py and 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

#3


14  

sys.argv is 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.argv will become a list ['file.py', 'something']

sys.argv将成为一个列表['file.py','something']

In this case sys.argv[1] = 'something'

在这种情况下,sys.argv [1] ='某事'

#4


11  

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”。

#5


6  

Adding a few more points to Jason's Answer :

再添加几点给杰森的答案:

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,则默认为list的长度。

Suppose you only want to take all the arguments after 3rd argument, then :

假设你只想在第三个参数之后获取所有参数,那么:

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 ":") :

假设你想要最后两个参数。这里,start是-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.

希望这可以帮助。

#6


3  

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]是您正在运行的脚本的路径,所有后续成员都是参数。

#7


2  

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

#8


0  

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将显示运行脚本时传递的命令行args,或者您可以说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, argv1 is the first argument passed, in this case 'example'

同样,argv1是传递的第一个参数,在本例中是'example'

A similar question has been asked already here btw. Hope this helps!

在这里已经有人问过类似的问题了。希望这可以帮助!