Python argv 验证

Python argv validation

我需要检查用户是否提供了输入文件和输出的名称,我正在执行以下操作:

def main():
    if len(argv) > 2:
        script, file_in, file_out = argv
        execute_code(file_in, file_out)
    else:
        print "Wrong number of arguments!"
        print "Usage: python script.py filename_input filename_output"


if __name__ == '__main__':
    main()

还有其他方法可以检查 argv 参数是否正确吗?

你会使用 argparse:

The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv.

例如,您的 main 函数可以重写为

import argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('file_in', help='input file')
    parser.add_argument('file_out', help='output file')
    args = parser.parse_args()
    execute_code(args.file_in, args.file_out)

if __name__ == '__main__':
    main()

argparse 将为您执行验证并在缺少某些必需参数时显示非常有用的错误消息:

vaultah@base:~$ python3 /home/vaultah/untitled.py
usage: untitled.py [-h] file_in file_out
untitled.py: error: the following arguments are required: file_in, file_out
vaultah@base:~$ python3 /home/vaultah/untitled.py in
usage: untitled.py [-h] file_in file_out
untitled.py: error: the following arguments are required: file_out

此外,它会生成一条帮助消息

vaultah@base:~$ python3 /home/vaultah/untitled.py -h
usage: untitled.py [-h] file_in file_out

positional arguments:
  file_in     input file
  file_out    output file

optional arguments:
  -h, --help  show this help message and exit

使用参数解析;理想情况下,使用 argparse.FileType 从命令行参数自动打开文件。

如果参数作为打开的文件没有意义,您可以捕获抛出的异常。

虽然要多做一些工作,但您可能要考虑使用 argparse

您的代码将变为:

import argparse

def execute_code(file_in, file_out):
    pass

def main():
    parser = argparse.ArgumentParser(description='Process some files.')
    parser.add_argument('file_in',  help='input file')
    parser.add_argument('file_out',  help='output file')
    args = parser.parse_args()
    execute_code(args.file_in, args.file_out)

if __name__ == '__main__':
    main()

运行 没有参数的程序: python demo.py

产量:

usage: demo.py [-h] file_in file_out
demo.py: error: the following arguments are required: file_in, file_out

运行带有-h标志的程序:

python demo.py -h

产量:

usage: demo.py [-h] file_in file_out

Process some files.

positional arguments:
  file_in     input file
  file_out    output file

optional arguments:
  -h, --help  show this help message and exit

您还可以指定选项 required=True 使参数成为必需的。如果未指定必需的参数,这将引发错误。这是一个例子:

parser.add_argument("--required_arg",
                    required=True,
                    help="The argument which is mandatory")

检查输入输出文件的路径,可以使用如下代码:

 if not os.path.exists(file_name):
    error_message =  file_name + " does not exist \n";

您还可以查看 my blog Techable,了解有关 python 中参数解析器的更多信息。