Skip to content

Commit

Permalink
Add 4 default templates:
Browse files Browse the repository at this point in the history
CLI skeletons for Python 2.7 (argparse) and Python 2.6 and below (optparse). 
2 templates for the encoding magic comment.
  • Loading branch information
andreberg committed Jan 11, 2011
1 parent 6738830 commit 15868f3
Showing 1 changed file with 299 additions and 0 deletions.
299 changes: 299 additions & 0 deletions plugins/org.python.pydev/plugin.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2051,6 +2051,24 @@ for k in keyword.kwlist:

${prop} = property(**${prop}())${cursor}</pattern>
</template>
<template
autoinsert="true"
contextTypeId="org.python.pydev.editor.templates.python"
description="encoding comment"
icon="icons/template.gif"
id="org.python.pydev.editor.templates.python.encoding.comment"
name="cod">
<pattern># encoding: ${word_selection}</pattern>
</template>
<template
autoinsert="true"
contextTypeId="org.python.pydev.editor.templates.python"
description="encoding comment: utf-8"
icon="icons/template.gif"
id="org.python.pydev.editor.templates.python.encoding.comment.utf8"
name="codu8">
<pattern># encoding: utf-8</pattern>
</template>



Expand Down Expand Up @@ -2212,6 +2230,287 @@ if __name__ == "__main__":



<template
autoinsert="true"
contextTypeId="org.python.pydev.editor.templates.python.modules"
description="Module: Command line tool skeleton using argparse (suitable for Python 2.7+)"
icon="icons/template.gif"
id="org.python.pydev.editor.templates.python.module.cli.argparse"
name="Module: CLI (argparse)">
<pattern>#!/usr/local/bin/python2.7
# encoding: utf-8
'''
${module} -- ${shortdesc}

${module} is a ${description}

It defines ${classes_and_methods}

@author: ${user_name}

@copyright: ${year} ${organisation_name}. All rights reserved.

@license: Licensed under the Apache License, Version 2.0 (the "License");\n
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

U{http://www.apache.org/licenses/LICENSE-2.0}

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an B{"AS IS"} B{BASIS},
B{WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND}, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

@contact: ${user_email}
@deffield updated: Updated
'''

import sys
import os

from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter

__all__ = []
__version__ = 0.1
__date__ = '${isodate}'
__updated__ = '${isodate}'

DEBUG = 1
TESTRUN = 0
PROFILE = 0

class CLIError(Exception):
'''Generic exception to raise and log different fatal errors.'''
def __init__(self, msg):
super(CLIError).__init__(type(self))
self.msg = "E: %s" % msg
def __str__(self):
return self.msg
def __unicode__(self):
return self.msg

def main(argv=None): # IGNORE:C0111
'''Command line options.'''

if argv is None:
argv = sys.argv
else:
sys.argv.extend(argv)

program_name = "${module}" # IGNORE:W0612 @UnusedVariable
program_version = "v%s" % __version__
program_build_date = str(__updated__)
program_version_message = '%%(prog)s %s (%s)' % (program_version, program_build_date)
program_shortdesc = __import__('__main__').__doc__.split("\n")[1]
program_license = u'''%s

Created by ${user_name} on %s.
Copyright ${year} ${organisation_name}. All rights reserved.

Licensed under the Apache License 2.0
http://www.apache.org/licenses/LICENSE-2.0

Distributed on an "AS IS" basis without warranties
or conditions of any kind, either express or implied.

USAGE
''' % (program_shortdesc, str(__date__))

try:
# Setup argument parser
parser = ArgumentParser(description=program_license, formatter_class=RawDescriptionHelpFormatter)
parser.add_argument("-r", "--recursive", dest="recurse", action="store_true", help="recurse into subfolders [default: %(default)s]")
parser.add_argument("-v", "--verbose", dest="verbose", action="count", help="set verbosity level [default: %(default)s]")
parser.add_argument("-i", "--include", dest="include", help="only include paths matching this regex pattern. Note: exclude is given preference over include. [default: %(default)s]", metavar="RE" )
parser.add_argument("-e", "--exclude", dest="exclude", help="exclude paths matching this regex pattern. [default: %(default)s]", metavar="RE" )
parser.add_argument('-V', '--version', action='version', version=program_version_message)
parser.add_argument(dest="paths", help="paths to folder(s) with source file(s) [default: %(default)s]", metavar="path", nargs='+')

# Process arguments
args = parser.parse_args()

paths = args.paths
verbose = args.verbose
recurse = args.recurse
inpat = args.include
expat = args.exclude

if verbose &gt; 0:
print "Verbose mode on"
if recurse:
print "Recursive mode on"
else:
print "Recursive mode off"

if inpat and expat and inpat == expat:
raise CLIError("include and exclude pattern are equal! Nothing will be processed.")

for inpath in paths:
### do something with inpath ###
print inpath
return 0
except KeyboardInterrupt:
### handle keyboard interrupt ###
return 0
except Exception, e:
if DEBUG or TESTRUN:
raise(e)
print &gt;&gt; sys.stderr, sys.argv[0].split("/")[-1] + ": " + unicode(e).decode('unicode_escape')
print &gt;&gt; sys.stderr, "\t for help use --help"
return 2

if __name__ == "__main__":
if DEBUG:
sys.argv.append("-h")
sys.argv.append("-v")
sys.argv.append("-r")
if TESTRUN:
import doctest
doctest.testmod()
if PROFILE:
import cProfile
import pstats
profile_filename = '${module}_profile.txt'
cProfile.run('main()', profile_filename)
statsfile = open("profile_stats.txt", "wb")
p = pstats.Stats(profile_filename, stream=statsfile)
stats = p.strip_dirs().sort_stats('cumulative')
print &gt;&gt; statsfile, stats.print_stats()
statsfile.close()
sys.exit(0)
sys.exit(main())
</pattern>
</template>







<template
autoinsert="true"
contextTypeId="org.python.pydev.editor.templates.python.modules"
description="Module: Command line tool skeleton using optparse (suitable for Python &lt; 2.6)"
icon="icons/template.gif"
id="org.python.pydev.editor.templates.python.module.cli.optparse"
name="Module: CLI (optparse)">
<pattern>#!/usr/bin/env python
# encoding: utf-8
'''
${module} -- ${shortdesc}

${module} is a ${description}

It defines ${classes_and_methods}

@author: ${user_name}

@copyright: ${year} ${organisation_name}. All rights reserved.

@license: Licensed under the Apache License, Version 2.0 (the "License");\n
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

U{http://www.apache.org/licenses/LICENSE-2.0}

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an B{"AS IS"} B{BASIS},
B{WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND}, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

@contact: ${user_email}
@deffield updated: Updated
'''

import sys
import os

from optparse import OptionParser

__all__ = []
__version__ = 0.1
__date__ = '${isodate}'
__updated__ = '${isodate}'

DEBUG = 1
TESTRUN = 0
PROFILE = 0

def main(argv=None):
'''Command line options.'''

program_name = os.path.basename(sys.argv[0]) # IGNORE:W0612 @UnusedVariable
program_version = u"v0.1"
program_build_date = u"%s" % __updated__

program_version_string = u'%%prog %s (%s)' % (program_version, program_build_date)
#program_usage = u'''usage: spam two eggs''' # optional - will be autogenerated by optparse
program_longdesc = u'''''' # optional - give further explanation about what the program does
program_license = u"Copyright ${year} ${user_name} (${organisation_name}) \
Licensed under the Apache License 2.0\nhttp://www.apache.org/licenses/LICENSE-2.0"

if argv is None:
argv = sys.argv[1:]
try:
# setup option parser
parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license)
parser.add_option("-i", "--in", dest="infile", help="set input path [default: %default]", metavar="FILE")
parser.add_option("-o", "--out", dest="outfile", help="set output path [default: %default]", metavar="FILE")
parser.add_option("-v", "--verbose", dest="verbose", action="count", help="set verbosity level [default: %default]")

# set defaults
parser.set_defaults(outfile=u"./out.txt", infile=u"./in.txt")

# process options
(opts, args) = parser.parse_args(argv)

if opts.verbose &gt; 0:
print "verbosity level = %d" % opts.verbose
if opts.infile:
print u"infile = %s" % opts.infile
if opts.outfile:
print u"outfile = %s" % opts.outfile

# MAIN BODY #

except Exception, e:
print &gt;&gt; sys.stderr, sys.argv[0].split(u"/")[-1] + u": " + unicode(e).decode('unicode_escape')
print &gt;&gt; sys.stderr, "\t for help use --help"
return 2


if __name__ == "__main__":
if DEBUG:
sys.argv.append("-h")
if TESTRUN:
import doctest
doctest.testmod()
if PROFILE:
import cProfile
import pstats
profile_filename = '${module}_profile.txt'
cProfile.run('main()', profile_filename)
statsfile = open("profile_stats.txt", "wb")
p = pstats.Stats(profile_filename, stream=statsfile)
stats = p.strip_dirs().sort_stats('cumulative')
print &gt;&gt; statsfile, stats.print_stats()
statsfile.close()
sys.exit(0)
sys.exit(main())
</pattern>
</template>








</extension>

</plugin>

0 comments on commit 15868f3

Please sign in to comment.