python - 设置并要求默认 Python 脚本 OptionParser

标签 python arguments optionparser

以下“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")

谢谢。

<小时/>

更新了带有回溯错误的代码

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

最佳答案

我会做这样的事情:

from optparse import OptionParser
import sys

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()
    # rest of program...

if __name__ == '__main__':
    main()

因此我们设置了解析器和选项,然后检查是否有任何命令行输入。
如果没有,我们打印帮助消息并退出。否则我们继续执行程序。

当不使用命令行参数运行时,输出为:

Usage: your_script_name_here.py [options] arg

Options:
  -h, --help            show this help message and exit
  -d DIRECTORY, --directory=DIRECTORY
                        specify directory
  -f FILENAME, --file=FILENAME
                        specify file
  -v, --version         displays the version number
<小时/>

编辑(响应更新的代码):
空格/缩进在 Python 中很重要。
确保代码的其余部分缩进,使其属于 main() 函数。
filenames_or_wildcards = [] 开始,您的代码超出了 main() 函数的范围,因此没有名为 args 的变量>.

关于python - 设置并要求默认 Python 脚本 OptionParser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5359306/

相关文章:

shell - 如何将Jenkins凭证传递给Dockerfile/Shell?

ruby - 如何在 ruby​​ 的 OptionParser 中使用变量参数

python - 删除包含数组中内容的 pandas DataFrame 行

python - 在 Raspberry PI 上构建时出现 OpenCV 错误

python - 在 Python 中将多个参数传递给 C 函数

c - 指针上的 sizeof

ruby - 如何使用 Ruby OptionParser 指定所需的开关(不是参数)?

scala - 在 Scala 中扩展 Scopt OptionParser

python - 为什么 scikit-learn 对不同的回归器要求不同的数据形状?

python - 匹配 python 正则表达式中的复杂表达式