无法识别命令行参数

2024-06-16 12:13:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图发送一些命令行参数到我写的程序。我修改了在教程中找到的一些代码。然而,只有最后的论点,我送seam要通过。例如,如果我在中键入以下内容:

python test.py -m A

但是,如果我输入:

python test.py -s A

列表中的最后一个参数很有用。。。(代码附后)

import sys, getopt

def main(argv):
    mina = ""
    capsize= ""
    matchcharge= ""
    steps= ""

try:
    opts, args = getopt.getopt(argv,"m:cs:mc:s:",["min=","capsize=","matchcharge=","steps="])
except getopt.GetoptError:
    print("argument not recognised")
    sys.exit(2)
for opt, arg in opts:
    if opt == ("-m", "--min"):
        mina = arg
        print("1")
    elif opt in ("-cs", "--capsize"):
        capsize = arg
        print("2")
    elif opt in ("-mc", "--matchcharge"):
        matchcharge = arg
        print("3")
    elif opt in ("-s", "--steps"):
        steps = arg
        print("4")

print("mina " + str(min))
print("capsize" + str(capsize))
print("matchcharge" + str(matchcharge))
print("steps " + str(steps))


if __name__ == "__main__":
   main(sys.argv[1:])

Tags: inmainsysargstepsminprintopt
1条回答
网友
1楼 · 发布于 2024-06-16 12:13:03

在你的代码里

if opt == ("-m", " min"):

哪个应该是

if opt in ("-m", " min"):

既然你在其他地方都有这个权利,我想这已经被遗忘了。你知道吗

相关问题 更多 >