Skip to main content

Partial command line handler

Project description

cmdline

  • a tiny unsophisticated partial command line parser

Objective

This package was written to allow parsing of parts of a command line, just pre-commandline arguments to a command.

It is originally written as a front-end command pre-processor for arguments passed to Django's manage.py, not swallowing the entire command line but allowing some options to be parsed and actioned before the main show, without interfering with the specific command being executed.

This allows, for example, setting internal or environment variables, modifying or setting the DJANGO_SETTINGS_MODULE variable or any other use that can be imagined.

Parsing rules are a simplified version of what are accepted as POSIX rules for command line processing.

  • Both short '-x' and long '--xoption' are supported
  • Short options can be concatenated, but to avoid ambiguity any option that requires an argument are consumed consecutively from subsequent arguments and cannot be appended to the short opt itself
  • The form --longopt=argument is supported
  • Optional arguments are not supported
  • Evaluation order is significant and is exactly as specified on the command line.
  • You can't mix arguments with command arguments, the parser quits when a command is encountered and preserves all arguments following that command

The Option class used in option specifications are NamedTuples which is very compact.

Example (based on Django manage.py generated by cookiecutter-django):

#!/usr/bin/env python3
"""
Usage: manage.py [-e <env>] [-d] [-o] [-h] <other manage.py args>
 -e --env <environment>   set runtime environment local, production
 -d --docker              set internal configuration for docker
 -o --dotenv              enhanced configuration via .env
 -h --help                display this help
"""
import os
import sys
from cmdline import Option, system_args


if __name__ == "__main__":
   opts = [
       Option('e', 'env', has_arg=True),   # -e or --env switch
       Option('d', 'docker'),              # -d or --docker
       Option('o', 'dotenv'),              # -o or --dotenv
       Option('h', 'help'),                # -h or --help
   ]
   environ = 'local'   # default
   docker = False
   read_dotenv = '0'
   settings = dict(prog=sys.argv[0])

   def process_args(option: Option, key, arg):
       if not option:  # use 2nd arg to do something based on command invoked
           settings['prog'] = key
       elif option.short == 'e':
           settings['environ'] = arg
       elif option.short == 'd':
           settings['docker'] = True
       elif option.short == 'o':
           settings['read_dotenv'] = '1'
       elif option.short == 'h':
           print(__doc__)
           exit(0)

   def export(var, val):
       os.environ[var] = val

   system_args(opts, process_args)
   vars().update(settings)   

   default_settings = f'config.settings.{environ}'
   export('USE_DOCKER', 'yes' if docker else 'no')
   export('DOCKER_READ_DOT_ENV_FILE', read_dotenv)
           
   os.environ.setdefault("DJANGO_SETTINGS_MODULE", default_settings)

   try:
       from django.core.management import execute_from_command_line
   except ImportError:
       # The above import may fail for some other reason. Ensure that the
       # issue is really that Django is missing to avoid masking other
       # exceptions on Python 2.
       try:
           import django  # noqa
       except ImportError:
           raise ImportError(
               "Couldn't import Django. Are you sure it's installed and "
               "available on your PYTHONPATH environment variable? Did you "
               "forget to activate a virtual environment?"
           )

       raise

   execute_from_command_line(sys.argv)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cmdline-mini-1.0.2.tar.gz (5.5 kB view details)

Uploaded Source

Built Distribution

cmdline_mini-1.0.2-py3-none-any.whl (5.4 kB view details)

Uploaded Python 3

File details

Details for the file cmdline-mini-1.0.2.tar.gz.

File metadata

  • Download URL: cmdline-mini-1.0.2.tar.gz
  • Upload date:
  • Size: 5.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.11 CPython/3.10.0 Darwin/20.6.0

File hashes

Hashes for cmdline-mini-1.0.2.tar.gz
Algorithm Hash digest
SHA256 f0d98e330a1b0305145bff4cc86f02f03776d74f9d426f1f988d527162ef8819
MD5 144748f7055af15f716f3c6d142a6261
BLAKE2b-256 2b551f60486448bbb04361b550aaad141bd74cb8d91f4d7b64766d3ac7ac4d81

See more details on using hashes here.

File details

Details for the file cmdline_mini-1.0.2-py3-none-any.whl.

File metadata

  • Download URL: cmdline_mini-1.0.2-py3-none-any.whl
  • Upload date:
  • Size: 5.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.11 CPython/3.10.0 Darwin/20.6.0

File hashes

Hashes for cmdline_mini-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 e9b4a38e1aef004439c51dbf1cbe0470483b8533deb2b1a102ff3b8c076acb95
MD5 150657b8801d03fa2adf40bd74ea8e4e
BLAKE2b-256 eb97638b51330137874d0d9c44f60fb7d7721e2c3f40f3df4fe8de6d8d1ee751

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page