Python sys.argv[1], IndexError: 列表索引超出范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31689100/
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-19 10:25:41  来源:igfitidea点击:

sys.argv[1], IndexError: list index out of range

python

提问by DataGuy

I am having an issue with the following section of Python code:

我在 Python 代码的以下部分遇到问题:

# Open/Create the output file
with open(sys.argv[1] + '/Concatenated.csv', 'w+') as outfile:

    try:
        with open(sys.argv[1] + '/MatrixHeader.csv') as headerfile:
            for line in headerfile:
                outfile.write(line + '\n')
    except:
        print 'No Header File'

Specifically the error is as follows:

具体错误如下:

Traceback (most recent call last): File "ConcatenateFiles.py", line 12, in <module> with open(sys.argv[1] + 'Concatenated.csv', 'w+') as outfile:
IndexError: list index out of range

I've done some research and it seems that the sys.argvmight require an argument at the command line when running the script, but I'm not sure what to add or what the issue might be! I've also searched the site, but all of the solutions I've found either have no comments and/or don't include the open function as mine does.

我做了一些研究,似乎sys.argv在运行脚本时在命令行中可能需要一个参数,但我不确定要添加什么或可能是什么问题!我也搜索过该网站,但我发现的所有解决方案都没有评论和/或不像我的那样包含 open 功能。

Any help is greatly appreciated.

任何帮助是极大的赞赏。

采纳答案by Steve O'Driscoll

sys.argvrepresents the command line options you execute a script with.

sys.argv代表您用来执行脚本的命令行选项。

sys.argv[0]is the name of the script you are running. All additional options are contained in sys.argv[1:].

sys.argv[0]是您正在运行的脚本的名称。所有附加选项都包含在sys.argv[1:].

You are attempting to open a file that uses sys.argv[1](the first argument) as what looks to be the directory.

您正在尝试打开一个使用sys.argv[1](第一个参数)作为目录的文件。

Try running something like this:

尝试运行这样的东西:

python ConcatenateFiles.py /tmp

回答by Paul

I've done some research and it seems that the sys.argv might require an argument at the command line when running the script

我做了一些研究,似乎 sys.argv 在运行脚本时可能需要在命令行中输入一个参数

Not might, but definitely requires. That's the whole point of sys.argv, it contains the command line arguments. Like any python array, accesing non-existent element raises IndexError.

不是可能,但绝对需要。这就是 的重点sys.argv,它包含命令行参数。像任何 python 数组一样,访问不存在的元素会引发IndexError.

Although the code uses try/exceptto trap some errors, the offending statement occurs in the first line.

尽管代码用于try/except捕获一些错误,但有问题的语句出现在第一行。

So the script needs a directory name, and you can test if there is one by looking at len(sys.argv)and comparing to 1+number_of_requirements. The argv always contains the script name plus any user supplied parameters, usually space delimited but the user can override the space-split through quoting. If the user does not supply the argument, your choices are supplying a default, prompting the user, or printing an exit error message.

所以脚本需要一个目录名,你可以通过查看len(sys.argv)和比较 1+number_of_requirements来测试是否有目录名。argv 始终包含脚本名称以及任何用户提供的参数,通常以空格分隔,但用户可以通过引用覆盖空格分割。如果用户不提供参数,您的选择是提供默认值、提示用户或打印退出错误消息。

To print an error and exit when the argument is missing, add this line before the first use of sys.argv:

要在缺少参数时打印错误并退出,请在第一次使用 sys.argv 之前添加以下行:

if len(sys.argv)<2:
    print "Fatal: You forgot to include the directory name on the command line."
    print "Usage:  python %s <directoryname>" % sys.argv[0]
    sys.exit(1)

sys.argv[0]always contains the script name, and user inputs are placed in subsequent slots 1, 2, ...

sys.argv[0]始终包含脚本名称,用户输入放置在后续的插槽 1、2、...

see also:

也可以看看:

回答by lemonhead

sys.argvis the list of command line arguments passed to a Python script, where sys.argv[0]is the script name itself.

sys.argv是传递给 Python 脚本的命令行参数列表,其中sys.argv[0]是脚本名称本身。

It is erroring out because you are not passing any commandline argument, and thus sys.argvhas length 1 and so sys.argv[1]is out of bounds.

这是错误的,因为您没有传递任何命令行参数,因此sys.argv长度为 1,因此sys.argv[1]超出范围。

To "fix", just make sure to pass a commandline argument when you run the script, e.g.

要“修复”,只需确保在运行脚本时传递命令行参数,例如

python ConcatenateFiles.py /the/path/to/the/directory

However, you likely wanted to use some default directory so it will still work when you don't pass in a directory:

但是,您可能想使用一些默认目录,这样当您不传入目录时它仍然可以工作:

cur_dir = sys.argv[1] if len(sys.argv) > 1 else '.'

with open(cur_dir + '/Concatenated.csv', 'w+') as outfile:

    try:
        with open(cur_dir + '/MatrixHeader.csv') as headerfile:
            for line in headerfile:
                outfile.write(line + '\n')
    except:
        print 'No Header File'