python - 使用 getopt 的命令行选项和参数

标签 python command-line arguments getopt

我正在尝试用 python 编写一段代码,以使用 getopt 模块获取命令行选项和参数。 这是我的代码:

import getopt
import sys

def usage ():
    print('Usage')

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'xy:')
    except getopt.GetoptError as err:
        print(err)
        usage()
        sys.exit()

    for o,a in opts:
        if o in ("-x", "--xxx"):
            print(a)
        elif o in ("-y", "--yyy"):
            print(a)
        else:
            usage()
            sys.exit()

if __name__ == "__main__":
    main()

问题是我无法读取选项x 的参数,但我可以读取y 的参数。我应该怎么做才能解决这个问题?

最佳答案

试试 getopt.getopt(sys.argv[1:], 'x:y:')

http://docs.python.org/library/getopt.html

Parses command line options and parameter list. args is the argument list to be parsed, without the leading reference to the running program. Typically, this means sys.argv[1:]. options is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (':'; i.e., the same format that Unix getopt() uses).

关于python - 使用 getopt 的命令行选项和参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6562616/

相关文章:

python - 为什么我定义的语法不使用标记?

python - 为 Tkinter 小部件启用 "setgrid"选项

python - 是否有任何 numpy 按功能分组?

python - Windows 无法将参数传递给 python 脚本

shell - 如何在 Google Colab 中运行 shell(终端)?

powershell - Start-Job 脚本 block ——如何调用带参数的 cmdlet?

python - 运行程序一分钟然后暂停一分钟的最简单方法是什么

c# - 忽略 C# 命令行程序中的 try block

java - 如何将参数传递给线程

variables - 试图了解如何将参数从 gradle 传递到我的 shell 脚本?