Tuesday, November 3, 2015

sample argument parsing without library

#!/usr/bin/env python
import sys, os
import subprocess
import argparse

# Descriptive argument parsing using argparse
parser = argparse.ArgumentParser()
parser.add_argument('file_name')

args, unknown = parser.parse_known_args()

#print args
#print unknown







help_string = """
Purpose of the script:
1. make one or more file executable

Usage: python change_user <file_name or wild card for file names>

Note:

Arguments:
file_name: file_name = arg1

Help: make_exe.py help
"""
# example command = chmod +x *.py
CMD = ['chmod']

if ((len(sys.argv) > 1) and (sys.argv[1]== "help")):
    print help_string
    quit()
# 1 arguments required
if ((len(sys.argv)) < 2):
    print "Not enough arguments provided."
    exit(2)

arg1 = sys.argv[1].decode('string-escape')
print sys.argv[1]
print "HERE IS THE PRINT: " + arg1


status_success = 'operation completed successfully'
status_error = 'operation failed'
class CommandError(Exception):
    def __init__(self, cmd, retcode, out):
        self.cmd = cmd
        self.retcode = retcode
        self.out = out
        Exception.__init__(
            self,
            'Command "%s" failed with retcode %s (%s)' % (' '.join(cmd), retcode, out,)
            )

def read_cmd_output(args, input=None, keepends=False, **kw):
    """Read the output of a the given command."""
    return read_output(CMD + args, input=input, keepends=keepends, **kw)

def read_cmd_lines(args, keepends=False, **kw):
    """Return the lines output by p4 command.
    Return as single lines, with newlines stripped off."""
    return read_cmd_output(args, keepends=True, **kw).splitlines(keepends)

def read_output(cmd, input=None, keepends=False, **kw):
    if input:
        stdin = subprocess.PIPE
    else:
        stdin = None
    p = subprocess.Popen(
        cmd, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kw
        )
    (out, err) = p.communicate(input)
    retcode = p.wait()
    if retcode:
        raise CommandError(cmd, retcode, out)
    if not keepends:
        out = out.rstrip('\n\r')
    return out + err

def base_function():
    validate  = os.path.exists(arg1)
    if validate:
        out = read_cmd_output(
            ['+x', arg1],
            )
        # display output
        if out != "":
            print out
        print status_success
    else:
        print status_error

def main(args):
    base_function()

if __name__ == '__main__':
    main(sys.argv[1:])

No comments:

Post a Comment