如何在pyhton中的getopt()中使用shortopts

发布于 2025-01-16 21:22:54 字数 1180 浏览 2 评论 0原文

我无法理解 Shortops 中分号的含义。我有这样一个 longopt ["help", "runNum=","allplots=","sys=","re​​dblue=","signalinj=","ranking="] 我分配参数值

try:
    opts, args = getopt.getopt(sys.argv[1:],"h:", ["help","runNum=","allplots=","sys=","redblue=","signalinj=","ranking="])
except getopt.GetoptError:
    print("Bad option. ")
    sys.exit(2)

for o, a in opts:
    if o=="-h" or o=='--help':
        print("Ex: python3 app.py --runNum=55 --allplots=1 --sys=1 --ranking=0 --redblue=0 --signalinj=0")
    elif o=="--runNum":
        runNum = 'r'+str(a)
    elif o=='--allplots':
        _allplots=a
    elif o=='--sys':
        _sysflag=a
    elif o=='--ranking':
        _ranking=a
    elif o=='--redblue':
        _redblueflag=a
    elif o=='--signalinj':
        _signal_inj=a

当我在没有任何 shotopts 的情况下使用 python3 app.py 运行应用程序时,它工作正常,但使用 - 选项运行会返回“错误选项”错误而不是<代码>“例如:python3 app.y ...”--help 返回 UnboundLocalError:赋值前引用的局部变量“runNum” 错误。那么我怎样才能让它打印“Ex:python3 app.y ...”

我也尝试了 "h:o" 但没有任何改善。这种分号的用法对我来说仍然是个谜。如果有人能解释这一点并告诉我要在快捷方式上添加什么,我将不胜感激。

I'm having trouble understanding the meaning of semi-colons in shortops. I have such a longopt ["help", "runNum=","allplots=","sys=","redblue=","signalinj=","ranking="] and I assign values to parameters with

try:
    opts, args = getopt.getopt(sys.argv[1:],"h:", ["help","runNum=","allplots=","sys=","redblue=","signalinj=","ranking="])
except getopt.GetoptError:
    print("Bad option. ")
    sys.exit(2)

for o, a in opts:
    if o=="-h" or o=='--help':
        print("Ex: python3 app.py --runNum=55 --allplots=1 --sys=1 --ranking=0 --redblue=0 --signalinj=0")
    elif o=="--runNum":
        runNum = 'r'+str(a)
    elif o=='--allplots':
        _allplots=a
    elif o=='--sys':
        _sysflag=a
    elif o=='--ranking':
        _ranking=a
    elif o=='--redblue':
        _redblueflag=a
    elif o=='--signalinj':
        _signal_inj=a

When I run the app with python3 app.py without any shotopts, it works fine but running with - option returns "Bad option" error instead of "Ex: python3 app.y ..." and --help returns UnboundLocalError: local variable 'runNum' referenced before assignment error. So how can I make it print "Ex: python3 app.y ...".

I also tried "h:o" but no improvement. This semi colon usage is still a mystery to me. i appreciate it if someone can explain this and tell me what to put on shortopts.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文