My thoughts on python2.6 command line app template

Feature

Source

simple.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL)

import sys

from logging import getLogger, StreamHandler, Formatter

logger = getLogger(__name__)

def global_loginit(logname=__name__, format="%(message)s", stream=sys.stderr, level=20, datefmt="%Y-%m-%dT%H:%M:%S" ):
    _logger = getLogger(logname)
    _logger.setLevel(level)
    _handle = StreamHandler(stream)
    _handle.setFormatter(Formatter(fmt=format,datefmt=datefmt))
    _logger.addHandler(_handle)
    return _logger

def main(opts):
    logger.info("Python {0}".format(sys.version))
    logger.warning("{0}".format(opts))
    logger.info("{0}".format(opts))
    logger.debug("{0}".format(opts))
    opts["consolelogger"].info("This is it")

def options(opt, add_func, help_tail):
  optadd=add_func(opt)
  optadd('-P', '--prof', default=False, action='store_true', help='get profile' + help_tail )
  optadd('-D', '--Debug', default=False, action='store_true', help='log debug' + help_tail)
  optadd('-Q', '--Quiet', default=False, action='store_true', help='log quiet' + help_tail)
  if type(opt).__name__.startswith("Arg"):
    optadd("args", type=str, nargs='*')
  return opt

def parsed_opts():
  try:
    import argparse
    description= "test"
    epilog = """epilog
    """
    opt = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=description, epilog=epilog)
    add_func = lambda x: x.add_argument
    parsefunc = lambda x: dict(vars(x))
    help_tail=''
  except ImportError as e:
    import optparse
    opt = optparse.OptionParser()
    add_func = lambda x: x.add_option
    parsefunc = lambda x: dict(vars(x[0]).items() + [('args', x[1])])
    help_tail=' [default: %default]'
  return parsefunc( options(opt, add_func, help_tail).parse_args())


if __name__ == '__main__':
    opts = parsed_opts()

    loggercfg = {
      "format": "%(asctime)s.%(msecs).03d %(process)d %(module).4s %(levelname).4s %(lineno)d/%(funcName)s %(message)s",
      "level": 20 if (not opts["Debug"] and not opts["Quiet"]) else 10 if opts["Debug"] else 30
    }
    global_loginit(**loggercfg)
    opts["consolelogger"] = global_loginit(logname=__name__+"console",stream=sys.stdout)

    if opts['prof']:
      import cProfile
      cProfile.run('main(opts)')
      sys.exit(0)
    main(opts)

Recommended Posts

My thoughts on python2.6 command line app template
Template for creating command line applications in Python
Run unix command on python
Broadcast on LINE using python
Use Python 3 introduced with command line tools on macOS Catalina
Command line argument processing (Python docopt)
Python standard module that can be used on the command line
[Python] Run Flask on Google App Engine
Decompose command arguments in one line in Python
Use Django's ImageField on App Engine / Python
You search commandlinefu on the command line
Build a command line app in Python to understand setup.py, argparse, GitHub Actions
Correspondence memo when the direction key cannot be used on the python command line
[Python] How to test command line parser click
How to receive command line arguments in Python
Quickly display the QR code on the command line
Vienna with Python + Flask web app on Jenkins
Tweet (API 1.1) on Google App Engine for Python
Arduino development on the command line: vim + platformio
Syntax highlighting on the command line using Pygments
[Introduction to Udemy Python3 + Application] 67. Command line arguments
Convert XLSX to CSV on the command line
Operate Route53 on the command line using AWS-CLI.
Think about the selective interface on the command line
My Numpy (Python)
My sys (python)
My pyproj (python)
My pandas (python)
My str (python)
Python on Windows
My pyautogui (python)
twitter on python3
python on mac
LINE heroku python
My PySide (Python)
How to pass arguments when invoking python script from blender on the command line
My shutil (python)
My matplotlib (python)
python argparse template
My linux command
My urllib (python)
My pyperclip (python)
My sklearn (python)
[My memo] python
Python on Windbg
My ConfigParser (Python)
My Webdriver (Python)
My arcpy (python)
Steps to use the AWS command line interface (Python / awscli) on Mac OS X
My win32gui (Python)
My os (python)
[Python] Tkinter template
Deploy a Python 3.6 / Django / Postgres web app on Azure
python2 series / 3 series, character code and print statement / command line
Specify a subcommand as a command line argument in Python
Yum command to access MySQL with Python 3 on Linux
Deploy a Django application on Google App Engine (Python3)
How to use Django on Google App Engine / Python
Make Python segfault on one line without using ctypes
Multiply PDF by OCR on command line on Linux (Ubuntu)
Python command line analysis library comparison (argparse, click, fire)