Is it possible to use Windows-style command line options with Python?

Viewed 118

Is it possible to make a Python script accept command-line options that are Windows-styled (namely, prefixed with "/" instead of "-"/"--" and using ":" to specify values of options instead of "=")?

So far, I have used argparse and managed to use "/" as a prefix, but I could not make it use ":" as a separator.

parser = argparse.ArgumentParser(prog='PROG', prefix_chars='/')
parser.add_argument('/f')
parser.add_argument('/bar')

#This works with =
print(parser.parse_args('/f X /bar=Y'.split())) #Namespace(bar='Y', f='X')
#Does not work with :
print(parser.parse_args('/f:X /bar:Y'.split())) #blows up
1 Answers

You can do it manually. I did this quick so it's in no way conclusive. It's just meant to outline how it's manually possible.

import sys

# List of switches to watch for
switches = ['test', 'blah', 'g']

if __name__ == '__main__':
    for arg in sys.argv:
        if arg[0] == '/':
            arg = arg[1:]  # Remove /
            if ':' in arg:
                a1, v1 = arg.split(':')  # Separate arg:value
            else:
                a1 = arg
                v1 = None
            # parse for whole words/letters that take values
            if a1 in switches:
                print(f'caught {a1}')
            if v1 is not None:
                print(f'^ and it\'s value {v1}')
            else:
                for op in range(0, len(arg)):
                    # Do whatever for switches
                    print(f'caught {arg[op]}')

Output of python test.py /fa /test:big /g:vals:

caught f
caught a
caught test
^ and it's value big
caught g
^ and it's value vals
Related