Question

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

Was it helpful?

Solution 2

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.

OTHER TIPS

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').

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top