python cmd命令 循环传参数_将参数从cmd传递给python脚本

我在

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)…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值