检查python中命令行参数的数量

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

Checking the number of command line arguments in python

pythoncommand-line-arguments

提问by mdmenard

I'm new to python. Still getting my feet wet. I'm trying to do something like this:

我是python的新手。还是把脚弄湿了。我正在尝试做这样的事情:

import sys

if ((len(sys.argv) < 3 or < len(sys.argv > 3)):
    print """\
This script will compare two files for something
and print out matches

Usage:  theScript firstfile secondfile
"""
    return

I want to do this at the beginning of the script to check for the right number of arguments. The problem is "return" doesn't work here. I could do some big if then statement I suppose, but was hoping to not have to do that. Not sure if there is any easier way. Any ideas?

我想在脚本的开头执行此操作以检查正确数量的参数。问题是“返回”在这里不起作用。我想我可以做一些大的 if then 语句,但希望不必这样做。不知道有没有更简单的方法。有任何想法吗?

回答by gariepy

Use sys.exit()to exit from a script.

使用sys.exit()从脚本退出。

import sys

if len(sys.argv) < 3 or  len(sys.argv > 3):
    print """\
This script will compare two files for something
and print out matches

Usage:  theScript firstfile secondfile
"""
    sys.exit(0)

回答by zondo

syshas a function called exit:

sys有一个函数叫做exit

sys.exit(1)

is probably what you want. Using 1tells the program calling your program that there was an error. You should probably consider writing to sys.stderrthe reason for the error.

可能是你想要的。Using1告诉调用您的程序的程序存在错误。您可能应该考虑写信sys.stderr说明错误的原因。