Search code examples
pythongetopt

Getting a Python command-line argument using "getopt" when there is no corresponding key


I'm writing a python program where I need to read various optional command-line arguments, and one REQUIRED argument (a string) that ideally would be the last argument on the command-line. When using getopt, I can read-in everything except this string unless I set it up to also require the use of a flag (let's say -s) preceding it, like this:

Usage: myProgram.py [options] -s "some string"

Options available:
    -x                                     # Turn on option X
    -y                                     # Turn on option Y
    -a "used-defined parameter 1"
    -b "used-defined parameter 2"
    -c "used-defined parameter 3"
    -d "used-defined parameter 4"
    -s "used-defined string" (REQUIRED)

where the code to process the arguments would be as follows:

    (opts, args) = getopt.getopt(argv[1:], 'xya:b:c:d:s:')

This will parse the arguments into the key-value pairs of the allowed command-line options.

Instead, I'd like to allow the user to enter it like this:

Usage: myProgram.py [options] "some string"

without the -s identifier. As it's written above, if the -s is not explicitly included, the getopt code won't capture that last string. I can't simply assume mystring = sys.argv[-1] because it could be a parameter for one of the other optional arguments. How should I modify the getopt line (or what extra step should I add) to capture that last string when there is no key to identify it, while not confusing it with another existing key?


Solution

  • The solution (as suggested by @tripleee) was to add a couple of additional lines to capture the remaining command-line arguments and assign them to the variable I needed to use in the code. Specifically:

        (opts, args) = getopt.getopt(argv[1:], 'xya:b:c:d:')
        if args != "":
            if len(args) == 1:
                myString = args[0]
            else:
                myString = " ".join(args)