python - Python optparse 中的有序选项

标签 python command-line-arguments optional-arguments

首先,我知道 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/

相关文章:

Python:运行外部命令时传递参数

python - 未知类型名称 'glp_long' (mac osx python, pyglpk)

c - 如何比较 C 中的字符串命令行参数?

python - undefined symbol : PyArray_API when using numpy and swig

c# - 如何使用 C# 在 python 中将字符串作为命令行参数传递

ocaml - 可选参数无法删除?

python - 以字典作为可选参数的函数 - Python

ios - 如何初始化具有从前面的 ViewController 传递的非可选属性的 Swift ViewController?

python - 从 numpy 矩阵中删除均值

python - 如何从 Python 中的线程获取返回值?