以下“parser.add_option”语句有效,但如果脚本在没有选项/参数的情况下运行,它不会抱怨。如果未指定选项/参数,我希望它默认显示帮助(-h / --help)。
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option('-d', '--directory',
action='store', dest='directory',
default=None, help='specify directory')
parser.add_option('-f', '--file',
action='store', dest='filename',
default=None, help='specify file')
parser.add_option('-v', '--version',
action="store_true", dest="show_version",
default=False, help='displays the version number')
(options, args) = parser.parse_args()
#if len(args) < 1:
# parser.error("incorrect number of arguments")
其次,如果我启用以下片段,即使指定选项/参数,我也会得到“错误:参数数量不正确”。
if len(args) < 1:
parser.error("incorrect number of arguments")
谢谢。
更新了下面带有 Traceback 错误的代码
def main():
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option('-d', '--directory',
action='store', dest='directory',
default=None, help='specify directory')
parser.add_option('-f', '--file',
action='store', dest='filename',
default=None, help='specify file')
parser.add_option('-v', '--version',
action="store_true", dest="show_version",
default=False, help='displays the version number')
if len(sys.argv) == 1:
parser.print_help()
sys.exit()
(options, args) = parser.parse_args()
#if options.show_version:
# prog = os.path.basename(sys.argv[0])
# version_str = "1.0"
# print "version is: %s %s" % (prog, version_str)
# sys.exit(0)
filenames_or_wildcards = []
# remove next line if you do not want allow to run the script without the -f -d
# option, but with arguments
filenames_or_wildcards = args # take all filenames passed in the command line
# if -f was specified add them (in current working directory)
if options.filename is not None:
filenames_or_wildcards.append(options.filename)
追溯
$ python boto-backup.py Traceback (most recent call last): File "boto-backup.py", line 41, in <module>
filenames_or_wildcards = args # take all filenames passed in the command line NameError: name 'args' is not defined