小智 15
你可以用optparse就可以了.您不需要使用argparse.
if options.foo is None: # where foo is obviously your required option
parser.print_help()
sys.exit(1)
Run Code Online (Sandbox Code Playgroud)
从您的问题尚不清楚,您是否正在使用(不建议使用的)optparse模块或其替代产品argparse模块。假设是后者,那么只要没有提供任何参数(或参数不足),只要您至少有一个位置参数,脚本就会打印出用法消息。
这是一个示例脚本:
import argparse
parser = argparse.ArgumentParser(description="A dummy program")
parser.add_argument('positional', nargs="+", help="A positional argument")
parser.add_argument('--optional', help="An optional argument")
args = parser.parse_args()
Run Code Online (Sandbox Code Playgroud)
如果我不带参数运行它,则会得到以下结果:
usage: script.py [-h] [--optional OPTIONAL] positional [positional ...]
script.py: error: too few arguments
Run Code Online (Sandbox Code Playgroud)
感谢@forkchop 的提示 parser.print_help() !!!
那么我想它可能是这样的?
import optparse
parser = optparse.OptionParser()
...
options, remainder = parser.parse_args()
if len(sys.argv[1:]) == 0:
print "no argument given!"
parser.print_help()
Run Code Online (Sandbox Code Playgroud)
小智 5
以下是我之前处理这种方法的方法:
import optparse
parser = optparse.OptionParser()
...
if len(sys.argv) == 1: # if only 1 argument, it's the script name
parser.print_help()
exit()
Run Code Online (Sandbox Code Playgroud)