检查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
Checking the number of command line arguments in python
提问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
sys
has a function called exit
:
sys
有一个函数叫做exit
:
sys.exit(1)
is probably what you want. Using 1
tells the program calling your program that there was an error. You should probably consider writing to sys.stderr
the reason for the error.
可能是你想要的。Using1
告诉调用您的程序的程序存在错误。您可能应该考虑写信sys.stderr
说明错误的原因。