gpt4 book ai didi

Python opts 命令行参数中的属性

转载 作者:行者123 更新时间:2023-12-01 04:21:03 32 4
gpt4 key购买 nike

在下面的代码中,我尝试解析命令行的参数:

import sys, getopt
opts, args = getopt.getopt(sys.argv[1:],'hs:c:i:I')
opts = dict(opts)

print opts
print args

if '-s-' in opts:
print opts['-s']

当我运行代码时,我得到:

{}
['python', 'Practice5.py', '-s', 'stop_list.txt', '-c', 'documents.txt', '-i', 'index.txt', '-I']

命令行是:

python Practice5.py -s stop_list.txt -c documents.txt -i index.txt -I

为什么选项有空值?

最佳答案

仅使用传递给 getopt 的实际参数进行测试,我得到了预期的行为:

>>> import getopt
>>> opts, args = getopt.getopt(['-s', 'stop_list.txt', '-c', 'documents.txt', '-i', 'index.txt', '-I'], 'hs:c:i:I')
>>> opts
[('-s', 'stop_list.txt'), ('-c', 'documents.txt'), ('-i', 'index.txt'), ('-I', '')]
>>> args
[]

the documentation :

args is the argument list to be parsed, without the leading reference to the running program.

如果您在 sys.argv 中还有 'python' 和您的脚本名称,则需要从其开头开始进行更多切片。您还可以考虑切换到 argparse,如 getopt 文档中的建议。

关于Python opts 命令行参数中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33692619/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com