Welcome, Guest! Registration


Friday, 2019-02-22
Main » 2012 » May » 1 » Python template for Linux command line script
1:41 AM
Python template for Linux command line script
Something for Python 2.6, work in progress.
#!/usr/bin/env python
"""loc2log template v.0.2
Template for a simple command line script, Python 2.6.

    <script_name> [-hvd]
    -v, --verbose
        Verbose output
    -d, --debug
        Debug level
    -h, --help
        This usage screen
import traceback
import os
import sys
import subprocess
import getopt
import datetime
import re

is_verbose = False
debug_level = 0

def usage(rc):
    """Show usage from 'About', then exit."""
    print globals()['__doc__']

def do(cmd):
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    (std, err) = p.communicate()
    # rc = p.returncode
    return std

def main():
        optlist, arglist = getopt.getopt(sys.argv[1:],
                                         ['help','h','verbose', 'debug'])
    except Exception, e:
        print >>sys.stderr, "[ERROR] Unexpected input."

    if len(optlist) == 0:
        print >>sys.stderr, "[ERROR] Missing input parameters."

    for opt, arg in optlist:
        if opt in ('-h','--help'):
            print 'Help:'
        elif opt in ('-v', '--verbose'):
            is_verbose = True
        elif opt in ('-d', '--debug'):
            debug_level = int(arg)
            print "debug_level=" + str(arg)
            print >>sys.stderr, "[ERROR] Unknown input parameter(s)."

if __name__ == "__main__":
    except KeyboardInterrupt:
        print("Keyboard interrupt.")
    except SystemExit:
    except Exception, e:
        print str(e)
For Python 2.7 or 3.2, the recommended way for handing command-line parameters is argparse instead of getopt. The latter does not handle optional parameters. Good reads:
getopt – Command line option parsing by Doug Hellman
Views: 2687 | Added by: loc2logg | Tags: Python, Linux | Rating: 3.5/2
Total comments: 0
Only registered users can add comments.
[ Registration | Login ]