一些 python argparse 使用问题:检索参数
我通过阅读文档无法弄清楚的一些问题和其他一些问题。
1:我被“如何实际检索参数”所困扰,所以我环顾四周,有人建议使用 __dict __ 函数像字典一样访问它。哪个有效,但这是唯一的方法吗?这似乎是一个相当常见的事情,但在文档中似乎并不明显。如果我错过了,也许有人可以指出来?它绝对不是在顶部。
2: argparse 是在 2.7 中引入的,但有些人拒绝获得较新版本的 python,并继续坚持使用较旧的版本,如 2.5、2.6,原因我不得而知。我处理它们的解决方案是采用 argparse 模块并将其放入我自己的脚本目录中。这个解决方案有什么问题吗?看起来至少是有效的。
Some questions that I couldn't figure out from reading the docs and some other questions.
1: I was stumped by "how do I actually retrieve the arguments" so I looked around and someone suggested to use the __dict __
function to access it like a dictionary. Which works, but is that the only way? This seems like a rather common thing but it doesn't appear to be anywhere obvious in the docs. If I missed it, maybe someone can point it out? It definitely wasn't at the top.
2: argparse
was introduced in 2.7, but some people refuse to get newer versions of python and continue to stick to older ones like 2.5, 2.6 for reasons unknown to me. My solution for dealing with them is to take the argparse
module and put it in my own script directory. Is there any problem with this solution? It seems to be working at least.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
parse_args()
函数来检索参数。例如:回答你的第二个问题,不建议你这样做。仅仅添加模块是不够的,因为您可能会遇到依赖性问题(即,在内部,argparse 可能需要其他仅在 2.7 中提供的东西)。较旧但已弃用的版本是 optparse。
You can use the
parse_args()
function to retrieve parameters. For example:To answer your second question, it's not recommended that you do this. Simply adding the module won't be sufficient since you might run into dependency issues (ie, internally, argparse may require something else that was only made available in 2.7). The older, but deprecated version of this is optparse.
广告 1:检索值非常简单:
现在可以使用
args.some_arg
或args.some_flag
访问这些值,如 文档。广告 2:由于 argparse 在 2.7 中引入,许多人坚持使用旧版本的 optparse 以实现向后兼容性,因为该模块可能不可用。语法非常相等。我的解决方案是尝试使用 argparse 进行解析并使用 optparse 作为后备。
Ad 1: Retrieving the values is pretty easy:
now the values can be accessed with
args.some_arg
orargs.some_flag
as can be seen in the documentation.Ad 2: Since argparse was introduced in 2.7 many people stick to the older version
optparse
for backwards compatibility since the module might not be available. The syntax is pretty equal. My solution is to try to parse withargparse
and useoptparse
as a fallback.