Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python get opt long option only

I want to use getopt to get input from command line argument with long option only

Example: ./script --empid 123

options, args = getopt.getopt(sys.argv[1:],['empid='])
    for opt, arg in options:
        print 'opts',opt
        if opt in ('--empid'):
            emp_Id = arg

I am getting the error getopt.GetoptError: option --empid not recognised error with the above code. What might have gone wrong?

like image 493
user2763829 Avatar asked Sep 28 '26 11:09

user2763829


1 Answers

you didn't read the documentation for getopt.getopt:

getopt.getopt(args, options[, long_options])

Parses command line options and parameter list. [...]

long_options, if specified, must be a list of strings with the names of the long options which should be supported. The leading -- characters should not be included in the option name. Long options which require an argument should be followed by an equal sign (=). Optional arguments are not supported. To accept only long options, options should be an empty string.

so you have to do:

options, args = getopt.getopt(sys.argv[1:], "", ['empid='])

Quoting from the documentation of getopt:

Note

The getopt module is a parser for command line options whose API is designed to be familiar to users of the C getopt() function. Users who are unfamiliar with the C getopt() function or who would like to write less code and get better help and error messages should consider using the argparse module instead.

Example of usage of argparse:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--empid', type=int)
parser.add_argument('positionals', nargs='*')
args = parser.parse_args()
print(args.positionals, args.empid)

This module is much more flexible, advanced and, at the same time, easier to use than getopt.

like image 186
Bakuriu Avatar answered Sep 30 '26 05:09

Bakuriu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!