Convert the result of python optparse to dict and utilize it

Basics of optparse

Optparse, a very useful module of Python, parse_argsObtained atoptionsIs 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.

dict

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))

As a keyword argument

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

Convert the result of python optparse to dict and utilize it
I want to batch convert the result of "string" .split () in Python
The result of making a map album of Italy honeymoon in Python and sharing it
It is easy to execute SQL with Python and output the result in Excel
How to convert Youtube to mp3 and download it super-safely [Python]
The process of making Python code object-oriented and improving it
I want to know the features of Python and pip
Overview of Python virtual environment and how to create it
The story of Python and the story of NaN
Return the image data with Flask of Python and draw it to the canvas element of HTML
Determine the date and time format in Python and convert to Unixtime
Made it possible to convert PNG to JPG with Pillow of Python
[Introduction to Python] I compared the naming conventions of C # and Python.
[Python] How to get the first and last days of the month
Read big endian binary in Python and convert it to ndarray
The result of installing python in Anaconda
Process the gzip file UNLOADed with Redshift with Python of Lambda, gzip it again and upload it to S3
Find the white Christmas rate by prefecture with Python and map it to a map of Japan
[Python] The role of the asterisk in front of the variable. Divide the input value and assign it to a variable
[Python] How to specify the window display position and size of matplotlib
I tried to verify and analyze the acceleration of Python by Cython
Read CSV file with Python and convert it to DataFrame as it is
[python] Send the image captured from the webcam to the server and save it
[Python / Jupyter] Translate the comment of the program copied to the clipboard and insert it in a new cell
Read the data of the NFC reader connected to Raspberry Pi 3 with Python and send it to openFrameworks with OSC
Convert "number" of excel date to python datetime
Summary of the differences between PHP and Python
View the result of geometry processing in Python
Specifying the range of ruby and python arrays
Compare the speed of Python append and map
How to convert SVG to PDF and PNG [Python]
List of Python code to move and remember
Convert the character code of the file with Python3
About the * (asterisk) argument of python (and itertools.starmap)
A discussion of the strengths and weaknesses of Python
How to pass the execution result of a shell command in a list in Python
Use Pillow to make the image transparent and overlay only part of it
An engineer who has noticed the emo of cryptography is trying to implement it in Python and defeat it
GAE --With Python, rotate the image based on the rotation information of EXIF and upload it to Cloud Storage.
Convert timezoned date and time to Unixtime in Python2.7
Easy way to check the source of Python modules
python beginners tried to predict the number of criminals
Python practice Convert the input year to the Japanese calendar
The wall of changing the Django service from Python 2.7 to Python 3
[Python] Convert decimal numbers to binary numbers, octal numbers, and hexadecimal numbers
Template of python script to read the contents of the file
The story of Python without increment and decrement operators.
How to get the number of digits in Python
[Python] Convert general-purpose container and class to each other
How to achieve access by attribute and retention of insertion order in Python dict
How to store Python function in Value of dictionary (dict) and call function according to Key
Python --Explanation and usage summary of the top 24 packages
[python] option to turn off the output of click.progressbar
Extract images and tables from pdf with python to reduce the burden of reporting
the zen of Python
I tried to automate the article update of Livedoor blog with Python and selenium.
About the usefulness of the Python Counter class-You don't have to count it yourself anymore-
Convert the image in .zip to PDF with Python
Get the result in dict format with Python psycopg2
Referencing and changing the upper bound of Python recursion
Convert dict to array