gpt4 book ai didi

python - Python 的 optparse 中的有序选项

转载 作者:行者123 更新时间:2023-11-28 23:06:26 25 4
gpt4 key购买 nike

首先,我知道 optparse 自 2.7 版以来已被弃用,但我正在工作的机器中只有 Python 2.3 可用。

问题是如何知道命令行中给出选项的顺序,例如:

python example.py -f foo -b bar

将首先执行选项 f,然后执行选项 b 和

python example.py -b bar -f foo

会做相反的事情。

我在阅读optargs 文档后想到的唯一解决方案是使用callback 操作来存储选项 检测相对位置到其他选项,因为 options 对象似乎不遵循任何特定顺序。

你知道这个问题的另一个(也许更好)解决方案吗?

最佳答案

拥有根据顺序触发不同行为的选项标志是违反惯例的。但是如果你真的想检查订单,你可以看看 sys.argv

#assuming both -f and -b are given in cmdline and you need to check for order
index_f = sys.argv.find("-f")
index_b = sys.argv.find("-b")
if index_f < index_b:
# do something if -f is before -b

关于python - Python 的 optparse 中的有序选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4994634/

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