加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

将参数从cmd传递给python脚本

发布时间:2020-12-20 11:27:35 所属栏目:Python 来源:网络整理
导读:我在 python中编写脚本并通过输入以下命令运行cmd: C: python script.py 我的一些脚本包含基于标志调用的单独算法和方法. 现在我想通过cmd直接传递标志,而不是必须进入脚本并在运行之前更改标志,我想要类似于: C: python script.py -algorithm=2 我读过
我在 python中编写脚本并通过输入以下命令运行cmd:

C:&; python script.py

我的一些脚本包含基于标志调用的单独算法和方法.
现在我想通过cmd直接传递标志,而不是必须进入脚本并在运行之前更改标志,我想要类似于:

C:&; python script.py -algorithm=2

我读过人们使用sys.argv几乎是类似的目的,但是阅读手册和论坛我无法理解它是如何工作的.

解决方法

有一些专门解析命令行参数的模块: getopt,optparseargparse.不推荐使用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)…

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读