Search code examples
pythonoptparse

Make optparse treat certain options as positional arguments


I have a program that takes in arguments of the form filename:field[slice], which works fine. But I also wish to support the common notation that a filename of - means standard input. Sadly, -:field[slice] registers as an option with optparse (naturally), and hence does not show up as a positional argument. So I'm wondering if there is a way to get around this, for example by telling optparse that options starting with -: should be treated as positional arguments after all. The solution should preserve the ordering of the arguments, so foo:bar -:cow baz:dog should not become foo:bar baz:dog -:cow.


Solution

  • It seems to me that your best option is to preprocess sys.argv inserting a special token which you check for instead of -.

    args = [ '<stdin>:'+x[2:] if x.startswith('-:') else x for x in sys.argv[1:] ]
    opt_struct = parser.parse_args(args)
    

    In this case, you would parse <stdin> as standard input in your program instead of -.

    The transform gets a little more complicated if the : and the stuff after it are optional, but this is the gist of it anyway.

    9 times out of 10, these problems are likely impossible to solve with optparse, really tricky/messy to solve with argparse and trivial to solve by preprocessing sys.argv -- But maybe that's just my experience ...