简体   繁体   English

python中的sys.argv:索引超出范围消息而不是我的错误消息

[英]sys.argv in Python: index out of range message instead of my error message

Normally I run this script fro the command line with one argument: python myscript.py argument 通常,我使用一个参数在命令行中运行此脚本:python myscript.py参数

But when this argument is lacking, I want the error message to be shown: 但是当缺少此参数时,我希望显示错误消息:

usage: myscript.py [file ...] 用法:myscript.py [文件...]

Script: 脚本:

import sys
from lxml import etree

filename = sys.argv[1]

tree = etree.parse(filename)

def f1():
...
def main():
   if len(sys.argv) < 2:
           print 'usage: extract.py [file ...]'
           sys.exit(1)

   else:
      f1()

Before I had this working, I could the error message in case there is no argument, but now it stopped working, I don't see why... I only get this message when I run the script without the argument from the command line: 在进行此工作之前,我可以在没有参数的情况下显示错误消息,但是现在它停止工作了,我不明白为什么...我只在运行脚本时在命令行中没有参数的情况下收到此消息:

Traceback (most recent call last):
  File "myscript.py", line 14, in <module>
    filename = sys.argv[1]
IndexError: list index out of range

The line filename = sys.argv[1] runs first . filename = sys.argv[1] 首先运行。 Your len() test is not reached. 您的len()测试未达到。

Move setting the filename and tree into the main() function, and don't use globals here: 将设置filenametree移到main()函数中,在这里不要使用全局变量:

def f1(tree):
    ...

def main():
    if len(sys.argv) < 2:
        print 'usage: extract.py [file ...]'
        sys.exit(1)

    filename = sys.argv[1]
    tree = etree.parse(filename)

    f1(tree)

if __name__ == '__main__':
    main()

As Martijn says, sys.argv[1] gets referenced before you test len() . 正如Martijn所说,在测试len()之前,已引用sys.argv[1]

I prefer to move the tests into the calling clause instead of main, like so: 我更喜欢将测试移到调用子句而不是main中,如下所示:

import sys
from lxml import etree

def f1(tree):
    pass

def main(filename):
    tree = etree.parse(filename)
    f1(tree)

if __name__=="__main__":
    if len(sys.argv) == 2:
        main(sys.argv[1])
    else:
        print 'usage: extract.py [file ...]'
        sys.exit(1)

I feel this provides a more logical division of responsibilities in the code. 我认为这在代码中提供了更合乎逻辑的职责划分。

rather than doing all this why not use argparse module from python. 而不是做所有这些,为什么不使用python中的argparse模块。 If the argument is not provided it will automatically print the usage statement as below 如果未提供参数,它将自动打印用法说明,如下所示

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', type=argparse.FileType('r'))
args = parser.parse_args()      
print(args.file)

type=argparse.FileType('r') argument is not necessary but it is better to use. type=argparse.FileType('r')参数不是必需的,但最好使用。

'r' represents and checks whether the file is readable or exists. 'r'代表并检查文件是否可读或存在。

Similarly you can use 'w' to check if file that you are passing is writable. 同样,您可以使用'w'检查所传递的文件是否可写。

Output: 输出:

$> python progargs.py $> python progargs.py

usage: progargs.py [-h] file 用法:progargs.py [-h]文件

progargs.py: error: too few arguments progargs.py:错误:参数太少

$> python progargs.py testanotherprog.py $> python progargs.py testanotherprog.py

'testanotherprog.py', mode 'r' at 0x7fe8ee422270> 'testanotherprog.py',模式为'r',位于0x7fe8ee422270>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python sys.argv [1]索引超出范围 - Python sys.argv[1] index out of range Sys.argv python错误列表索引超出范围 - Sys.argv python error list index out of range python sys.argv[1] 列表索引超出范围 - python sys.argv[1] list index out of range sys.argv列表索引超出范围错误 - sys.argv list index out of range error driver.get(sys.argv[1]) 在 PC 上正常工作,而在其他 PC 上工作正常(sys.argv[1],IndexError: list index out of range 错误) - driver.get(sys.argv[1]) working fine on a PC and not on the other (sys.argv[1], IndexError: list index out of range error) IndexError:列表索引超出范围:sys.argv[1] 超出范围 - IndexError: list index out of range: sys.argv[1] out of range 我在使用Python命令“ cascPath = sys.argv [1]”时遇到问题,出现错误IndexError:列表索引超出范围 - Iam having trouble with Python command “ cascPath = sys.argv[1] ” i get error IndexError: list index out of range sys.argv[1] 索引错误:列表索引超出范围 - sys.argv[1] IndexError: list index out of range 使用 sys.argv[1] 时“列表索引超出范围” - “list index out of range” when using sys.argv[1] Python GetHostId.py获取sys.argv [1] IndexError:列表索引超出范围 - Python GetHostId.py getting sys.argv[1] IndexError: list index out of range
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM