我在
python中编写脚本并通过输入以下命令运行cmd:
C:\> python script.py
我的一些脚本包含基于标志调用的单独算法和方法.
现在我想通过cmd直接传递标志,而不是必须进入脚本并在运行之前更改标志,我想要类似于:
C:\> python script.py -algorithm=2
我读过人们使用sys.argv几乎是类似的目的,但是阅读手册和论坛我无法理解它是如何工作的.
最佳答案 有一些专门解析命令行参数的模块:
getopt,
optparse和
argparse.不推荐使用optparse,并且getopt不如argparse强大,所以我建议你使用后者,从长远来看它会更有帮助.
这是一个简短的例子:
import argparse
# Define the parser
parser = argparse.ArgumentParser(description='Short sample app')
# Declare an argument (`--algo`), telling that the corresponding value should be stored in the `algo` field, and using a default value if the argument isn't given
parser.add_argument('--algo', action="store", dest='algo', default=0)
# Now, parse the command line arguments and store the values in the `args` variable
args = parser.parse_args()
# Individual arguments can be accessed as attributes...
print args.algo
这应该让你开始.在最糟糕的情况下,有大量的文档在线提供(例如,this one)…