Get options in Python from both JSON files and command line arguments

This is the Python version of another article, "Getting options in Ruby from both JSON files and command line arguments" (https://qiita.com/aikige/items/014139c0b1ae70139477). With the increasing use of Python these days, I'll share the results of my thoughts on how to write the same thing in Python.

Basic concept

  1. Collect options in one object. Example: class Options
  2. Read the options from the JSON file when creating the object. Example: opt = Options ('some.json') reads options from a JSON file.
  3. Use the object's attribute to access options. Example: You can access it like opt.option_1.
  4. Use Argparse to capture command line arguments.
  5. The optional object has a method that fetches the value from the result generated by Arguparse. Example: Import with something like opt.import_opt (options).

Implementation example

https://gist.github.com/aikige/470f4ef93753638cc3a18d62e195eb19

#!/usr/bin/env python

import json
import os

class Options:
    OPTS = { 'option_1': 'bool', 'option_2': 'str' }

    def __init__(self, filename='config.json'):
        if (os.path.exists(filename)):
            with open(filename) as f:
                self.import_dict(json.load(f))

    def import_attr(self, key, value):
        if (value is None):
            return
        if (isinstance(value, eval(self.OPTS[key]))):
            setattr(self, key, value)
        else:
            raise ValueError("invalid type")

    def import_dict(self, d):
        for key in self.OPTS.keys():
            if (key in d.keys()):
                self.import_attr(key, d[key])

    def import_opt(self, args):
        for key in self.OPTS.keys():
            if (hasattr(args, key)):
                self.import_attr(key, getattr(args, key))

if __name__ == '__main__':
    import argparse

    opt = Options()
    print(vars(opt))

    parser = argparse.ArgumentParser()
    parser.add_argument('-1', '--option_1', action='store_true', default=None)
    parser.add_argument('-2', '--option_2', type=str)
    args = parser.parse_args()
    print(vars(args))
    opt.import_opt(args)
    print(vars(opt))

Main differences from Ruby version

  1. Unlike Ruby, Python has a bool type, so it's relatively easy to incorporate type determination (import_attr).
  2. In case of Python, Arrgparse is used for option analysis, so JSON analysis and argument analysis methods are not unified. , Slightly redundant.
  3. In case of Python, it seems a little difficult to make attribute read-only, so I omitted it.

Recommended Posts

Get options in Python from both JSON files and command line arguments
Read and write JSON files in Python
Decompose command arguments in one line in Python
How to get a string from a command line argument in python
Reading and writing CSV and JSON files in Python
Load and execute command from yml in python
Get files, functions, line numbers running in python
Get files from Linux using paramiko and scp [Python]
[Python] Read command line arguments from file name or stdin
Get data from Quandl in Python
Manipulate files and folders in Python
Read and use Python files from Python
Handling of JSON files in Python
Export and output files in Python
Extract strings from files in Python
python Note: Determine if command line arguments are in the list
Get exchange rates from open exchange rates in Python
Line graphs and scale lines in python
Reading and writing JSON files with Python
Get battery level from SwitchBot in Python
Get Precipitation Probability from XML in Python
Get metric history from MLflow in Python
Reading from text files and SQLite in Python (+ Pandas), R, Julia (+ DataFrames)
Get time series data from k-db.com in Python
Template for creating command line applications in Python
[Python] Get the files in a folder with Python
Study from Python Reading and writing Hour9 files
How to get the files in the [Python] folder
[Introduction to Udemy Python3 + Application] 67. Command line arguments
POST JSON in Python and receive it in PHP
I want to get the file name, line number, and function name in Python 3.4
Get only articles from web pages in Python
How to pass arguments when invoking python script from blender on the command line
python2 series / 3 series, character code and print statement / command line
Specify a subcommand as a command line argument in Python
Include and use external Kv files in Python Kivy
Get data from GPS module at 10Hz in Python
How to download files from Selenium in Python in Chrome
Import classes in jar files directly from Python scripts
Get your current location and user agent in Python
Mutual conversion between JSON and YAML / TOML in Python
Get mail from Gmail and label it with Python3
Get stock prices and create candlestick charts in Python
Recursively search for files and directories in Python and output
Handling json in python
Execute command from Python
Get date in Python
Execute command from python
Get information such as GPU usage from Python (nvidia-smi command)
Compare HTTP GET / POST with cURL (command) and Python (programming)
Allow brew install of command line tools made in Python
Get your heart rate from the fitbit API in Python!
Search for large files on Linux from the command line
Get the MIME type in Python and determine the file format
Get the value while specifying the default value from dict in Python
How to specify command line arguments when debugging in PyCharm
Allow Python to select strings in input files from folders
Get the current date and time in Python, considering the time difference
Hit REST in Python to get data from New Relic
Predict gender from name using Gender API and Pykakasi in Python
Get macro constants from C (++) header file (.h) in Python