Optparse, a very useful module of Python,
parse_args
Obtained atoptions
Is not very easy to use
I feel that.
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import optparse
parser = optparse.OptionParser()
# option '-i'Add
parser.add_option('-o', '--output', type='str',
help='output filename')
#Parse command line arguments
options, args = parser.parse_args()
print(type(options))
To give an example, simply name the output file `-o``` or
--output``` OptionParser that can be specified as an option, This return value ```options``` is neither a dictionary nor anything,
<type'instance'>
`
An object of the type is returned.
To access the value of an option, use options.output
It will be in the form of accessing the Attribute.
If I could change this to dict, I could just throw it at the position of the keyword argument of the function.
That's why I will do it quickly.
Don't do anything difficult. Once converted to a character string as shown below, with the built-in function eval
If you interpret it as Python, you can convert it to `` `dict```.
options = eval(str(options))
If this happens, it will be easier to pass parameters to other functions.
def hogehoge(foo, fuga, **kwargs):
output = kwargs.get('output', sys.stdout)
hogehoge(foo, fuga, **options)
You can use it like an argument with a keyword like this. Need to add new parameters to the implemented algorithm It was a device that was useful for soberness, such as when it was completed.
Recommended Posts