howtechstuffworks
howtechstuffworks

Reputation: 1926

Multi-Character Command Parsing in Python getopt

I have been using python getopt for parsing, both short and long and it worked great. Now I need to add some more short variables in getopt function and it would look better, if I need to have multi characters as getopt:short. Is there a way to do something like this.

getopt.getopt(argv,"hf:c:d:pv:pz:","")

Here, I need to access pv and pz as a individual command line arguments instead of the getopt reading it as 'p with no args', 'v with one args'. I tried 'pv:' [pv:] inside the quotes, but it recognized pv, but does not read the args.

Also,(on a different note) is it possible to have more than one inputs for the same args. Please pardon me, if you this is a very simple answer.

Upvotes: 5

Views: 4452

Answers (1)

Ayrton Everton
Ayrton Everton

Reputation: 1339

Based on my understanding of the documentation and research I did when I needed the same thing as you, there is no way to do it. shortopts with prefix "-" only work with one character, for more than one character, you must use longopts, which use the prefix "--".

Example in python3:

import sys, getopt

try:
    opts, args = getopt.getopt(sys.argv[1:], 'c:d:', ['hf','pv','pz'])
except getopt.GetoptError as e:
    print(str(e))

for o, a in opts:
    print(o, ':', a)

Unfortunately, I think there is no way to put longopts with a required argument, but this can be solved with a manual check.

For more information, i recommend consulting the documentation: https://docs.python.org/3.1/library/getopt.html

Upvotes: 2

Related Questions