开发者

Some python argparse usage questions: retrieving arguments

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 开发者_Python百科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.


You can use the parse_args() function to retrieve parameters. For example:

parser = argparse.ArgumentParser(description="Test")
parser.add_argument('command')

parameters = parser.parse_args()
cmd = parameters.command

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.


Ad 1: Retrieving the values is pretty easy:

parser.add_argument('--some_arg', action='store')
parser.add_argument('--some_flag', action='store_true')

args = parser.parse_args()

now the values can be accessed with args.some_arg or args.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 with argparse and use optparse as a fallback.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜