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

我目前正在自学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()

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?

#!/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()

回答 0

我想指出,先前的答案对用户的知识做出了许多假设。该答案尝试在更多教程级别回答问题。

对于Python的每次调用,sys.argv都会自动生成一个字符串列表,这些字符串代表命令行上的参数(用空格分隔)。该名称来自C编程约定,其中argv和argc代表命令行参数。

在熟悉Python的同时,您将需要了解有关列表和字符串的更多信息,但是与此同时,这里需要了解一些事情。

您可以简单地创建一个脚本,该脚本在显示参数时将其打印出来。它还使用len列表上的函数打印参数的数量。

from __future__ import print_function
import sys
print(sys.argv, len(sys.argv))

该脚本需要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

如您所见,命令行参数包括脚本名称,但不包括解释器名称。从这个意义上讲,Python将脚本视为可执行文件。如果您需要知道可执行文件的名称(在这种情况下为python),可以使用sys.executable

从示例中可以看到,如果用户使用封装在引号中的参数调用脚本,则可能会收到包含空格的参数,因此您得到的是用户提供的参数列表。

现在,在Python代码中,您可以使用此字符串列表作为程序的输入。由于列表由从零开始的整数索引,因此您可以使用list [0]语法获取单个项目。例如,要获取脚本名称:

script_name = sys.argv[0] # this will always work.

尽管很有趣,但是您几乎不需要知道脚本名称。要在脚本后获取文件名的第一个参数,可以执行以下操作:

filename = sys.argv[1]

这是一种非常常见的用法,但是请注意,如果未提供任何参数,它将失败并显示IndexError。

另外,Python允许您引用列表的一部分,因此要获取仅由用户提供的参数的另一个列表(但没有脚本名称),您可以执行

user_args = sys.argv[1:] # get everything after the script name

此外,Python允许您将一系列项目(包括列表)分配给变量名称。因此,如果您希望用户始终提供两个参数,则可以将这些参数(作为字符串)分配给两个变量:

user_args = sys.argv[1:]
fun, games = user_args # len(user_args) had better be 2

因此,为回答您的特定问题,sys.argv[1]代表了string提供给相关脚本的第一个命令行参数(作为)。它不会提示输入,但是如果脚本名称后面的命令行上没有提供任何参数,它将失败并显示IndexError。

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.

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.

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.

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

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:

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.

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

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:

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.


回答 1

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

例如,如果您的脚本已命名hello.py并且发出:

$ python3.1 hello.py foo

要么:

$ chmod +x hello.py  # make script executable
$ ./hello.py foo

您的脚本将打印:

你好,富

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

For example, if your script is named hello.py and you issue:

$ python3.1 hello.py foo

or:

$ chmod +x hello.py  # make script executable
$ ./hello.py foo

Your script will print:

Hello there foo

回答 2

sys.argv 是一个列表。

此列表由您的命令行创建,它是您的命令行参数的列表。

例如:

在命令行中,您需要输入以下内容,

python3.2 file.py something

sys.argv 将成为列表[‘file.py’,’something’]

在这种情况下 sys.argv[1] = 'something'

sys.argv is a list.

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

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


回答 3

仅添加Frederic的答案,例如,如果您按以下方式调用脚本:

./myscript.py foo bar

sys.argv[0]将是“ ./myscript.py” sys.argv[1]将是“ foo”并且 sys.argv[2]将是“ bar” …依此类推。

在示例代码中,如果按以下方式调用脚本 ./myscript.py foo ,则脚本的输出将为“ Hello there foo”。

Just adding to Frederic’s answer, for example if you call your script as follows:

./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.

In your example code, if you call the script as follows ./myscript.py foo , the script’s output will be “Hello there foo”.


回答 4

在Jason的答案中添加更多点:

对于所有用户提供的参数: user_args = sys.argv[1:]

将sys.argv视为字符串列表(如Jason所述)。因此,所有列表操作都将在此处应用。这称为“列表切片”。有关更多信息,请访问此处

语法如下:list [start:end:step]。如果省略开始,则默认为0;如果省略结束,则默认为列表长度。

假设您只想在第3个参数之后采用所有参数,则:

user_args = sys.argv[3:]

假设您只需要前两个参数,然后:

user_args = sys.argv[0:2]  or  user_args = sys.argv[:2]

假设您需要参数2到4:

user_args = sys.argv[2:4]

假设您要使用最后一个参数(最后一个参数始终为-1,所以这里发生的事情是我们从后面开始计数。所以开始是last,no end,no step):

user_args = sys.argv[-1]

假设您要倒数第二个参数:

user_args = sys.argv[-2]

假设您需要最后两个参数:

user_args = sys.argv[-2:]

假设您需要最后两个参数。在这里,开始是-2,这是倒数第二个项目,然后到结尾(以“:”表示):

user_args = sys.argv[-2:]

假设您需要除最后两个参数以外的所有内容。在这里,开始是0(默认情况下),结束是倒数第二个项目:

user_args = sys.argv[:-2]

假设您希望参数以相反的顺序进行:

user_args = sys.argv[::-1]

希望这可以帮助。

Adding a few more points to Jason’s Answer :

For taking all user provided arguments : 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.

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.

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 :

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

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 “:”) :

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 :

user_args = sys.argv[:-2]

Suppose you want the arguments in reverse order :

user_args = sys.argv[::-1]

Hope this helps.


回答 5

sys.argv是一个包含脚本路径和命令行参数的列表;即sys.argv [0]是您正在运行的脚本的路径,以下所有成员都是参数。

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.


回答 6

通过命令行运行脚本时将参数传递给python脚本

python create_thumbnail.py test1.jpg test2.jpg

在这里,脚本名称-create_thumbnail.py,参数1-test1.jpg,参数2-test2.jpg

我在create_thumbnail.py脚本中使用

sys.argv[1:]

这给了我在命令行中以[‘test1.jpg’,’test2.jpg’]传递的参数列表

To pass arguments to your python script while running a script via command line

python create_thumbnail.py test1.jpg test2.jpg

here, script name – create_thumbnail.py, argument 1 – test1.jpg, argument 2 – test2.jpg

With in the create_thumbnail.py script i use

sys.argv[1:]

which give me the list of arguments i passed in command line as [‘test1.jpg’, ‘test2.jpg’]


回答 7

sys.argvsys模块的属性。它说参数是在命令行中传递到文件中的。sys.argv[0]捕获文件所在的目录。sys.argv[1]返回在命令行中传递的第一个参数。就像我们有一个example.py文件。

example.py

import sys # Importing the main sys module to catch the arguments
print(sys.argv[1]) # Printing the first argument

现在,当我们执行此操作时,在命令提示符下显示以下内容:

python example.py

它将在第2行引发索引错误。原因是尚未传递任何参数。您可以使用看到用户传递的参数的长度if len(sys.argv) >= 1: # Code。如果我们通过传递参数来运行example.py

python example.py args

它打印:

args

因为这是第一个参数!假设我们已经使用PyInstaller使其成为可执行文件。我们可以这样做:

example argumentpassed

它打印:

argumentpassed

在终端中执行命令时,这确实很有帮助。首先检查参数的长度。如果未传递任何参数,请执行帮助文本。

sys.argv is a attribute of the sys module. 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.

example.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

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:

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.


回答 8

sys .argv将显示运行脚本时传递的命令行参数,或者可以说sys.argv将存储从终端运行时在python中传递的命令行参数。

尝试一下:

import sys
print sys.argv

argv将所有传递的参数存储在python列表中。上面将打印所有传递的参数,将运行脚本。

现在尝试像这样运行您的filename.py:

python filename.py example example1

这将在列表中打印3个参数。

sys.argv[0] #is the first argument passed, which is basically the filename. 

同样,argv 1是传递的第一个参数,在这种情况下为“ example”

顺便说一句,这里已经提出了类似的问题。希望这可以帮助!

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.

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.

Now try this running your filename.py like this:

python filename.py example example1

this will print 3 arguments in a list.

sys.argv[0] #is the first argument passed, which is basically the filename. 

Similarly, argv1 is the first argument passed, in this case ‘example’

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


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。