1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script generation
:author: Michael Mulich
:copyright: 2010 by Penn State University
:organization: WebLion Group, Penn State University
:license: GPL, see LICENSE for more detail
"""
import os
import sys
import stat
from optparse import OptionParser
assert sys.version_info >= (2, 7), "Python >= 2.7 is required"
__version__ = '0.1.0'
script_template = """\
%(initialization)s
import %(module_name)s
if __name__ == '__main__':
%(module_name)s.%(callable)s(%(arguments)s)
"""
usage = "%prog [options] module callable script_name"
parser = OptionParser(usage=usage)
parser.add_option('-a', '--default-arguments', dest='arguments',
default='',
help="Arguments to call the callble with.",
metavar='ARGS')
parser.add_option('-i', '--init-code', dest='initialization',
default='',
help="Code that initializes the script or arguments",
metavar='CODE')
parser.add_option('-e', '--executable', dest='executable',
default='/usr/bin/env python',
help="An executable to call the script with... used in the "
"script's shabang line.",
metavar='EXEC')
parser.add_option('-d', '--directory', dest='directory',
default=os.curdir,
help="The directory where the output should go, defaults to "
"the current directory.",
metavar='DIR')
def main():
(options, args) = parser.parse_args()
try:
(module, callable, script_name) = args
except ValueError, err:
print('\n'.join([parser.get_usage(), repr(err)]))
sys.exit(1)
# Generate the contents of the script
shabang_line = '#!' + options.executable
script_body = script_template % dict(module_name=module,
callable=callable,
initialization=options.initialization,
arguments=options.arguments,
)
script_body = shabang_line + script_body
# Create and write to the script file
script_path = os.path.join(options.directory, script_name)
with open(script_path, 'w') as f:
f.write(script_body)
mode = (stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC | stat.S_IRGRP | stat.S_IXGRP)
os.chmod(script_path, mode)
if __name__ == '__main__':
main()
|