Python argparse: how to handle MacOSX `-psn` parameter

喜夏-厌秋 提交于 2020-01-04 12:17:39

问题


MacOSX launchd passes the -psn... parameter to applications. How can I tell argparse how to parse the parameter? It's basically -psn_([0-9]+)_([0-9]+) but I'm fine if it just parses -psn(\S*). Is that possible at all?

(See here for some documentation about the Process Serial Number (PSN). And here is my question about what to do with the parameter.)


回答1:


Looking at the structure of the psn argument, it's not possible to parse it with argparse without interfering with a possible "-p" argument (see @hpaulj's answer). So, I'd recommend to use partial parsing, and extract it from the list of remainders.




回答2:


I don't know what other arguments you need (I use Linux), but how about this (from an interactive Ipython session):

In [3]: parser.add_argument('-p')
Out[3]: _StoreAction(option_strings=['-p'], dest='p', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)

In [4]: parser.parse_args('-psn_123_455'.split())
Out[4]: Namespace(p='sn_123_455')

Then you can parse args.p as needed.

You can't use parser.add_argument('-psn') because only single letter options can have contiguous arguments. ('-psn _123_455','-psn=_123_455' work, but not '-psn_123_455').

If there are other uses for the -p flag, this would not work.


You can use a custom type to parse the argument, e.g.

def psntype(x):
    ret = re.match('sn_([0-9]+)_([0-9]+)',x)
    if ret is None:
        raise ValueError('bad -psn argument')
    return ret.groups()

parser=argparse.ArgumentParser()
parser.add_argument('-p',type=psntype)
print parser.parse_args('-psn_123_455'.split())
# Namespace(p=('123', '455'))
parser.parse_args('-psn_12355'.split())
# usage: ipython [-h] [-p P]
# error: argument -p: invalid psntype value: 'sn_12355'

the main advantage to doing the parsing with type is that argparse can raise an informative error (with usage). But your own post-argparse code can raise the same error (parser.error('bad -psn argument').



来源:https://stackoverflow.com/questions/19661298/python-argparse-how-to-handle-macosx-psn-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!