You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

167 lines
4.6 KiB

  1. #!/usr/local/bin/python2.7
  2. # encoding: utf-8
  3. '''
  4. bin.example_argparse_souce -- shortdesc
  5. bin.example_argparse_souce is a description
  6. It defines classes_and_methods
  7. @author: user_name
  8. @copyright: 2013 organization_name. All rights reserved.
  9. @license: license
  10. @contact: user_email
  11. @deffield updated: Updated
  12. '''
  13. import sys
  14. import os
  15. from argparse import ArgumentParser
  16. from argparse import RawDescriptionHelpFormatter
  17. from gooey.gooey_decorator import Gooey
  18. __all__ = []
  19. __version__ = 0.1
  20. __date__ = '2013-12-13'
  21. __updated__ = '2013-12-13'
  22. DEBUG = 0
  23. TESTRUN = 0
  24. PROFILE = 0
  25. class CLIError(Exception):
  26. '''Generic exception to raise and log different fatal errors.'''
  27. def __init__(self, msg):
  28. super(CLIError).__init__(type(self))
  29. self.msg = "E: %s" % msg
  30. def __str__(self):
  31. return self.msg
  32. def __unicode__(self):
  33. return self.msg
  34. @Gooey
  35. def main(argv=None): # IGNORE:C0111
  36. '''Command line options.'''
  37. if argv is None:
  38. argv = sys.argv
  39. else:
  40. sys.argv.extend(argv)
  41. program_name = os.path.basename(sys.argv[0])
  42. program_version = "v%s" % __version__
  43. program_build_date = str(__updated__)
  44. program_version_message = '%%(prog)s %s (%s)' % (program_version, program_build_date)
  45. program_shortdesc = __import__('__main__').__doc__.split("\n")[1]
  46. program_license = '''%s
  47. Created by user_name on %s.
  48. Copyright 2013 organization_name. All rights reserved.
  49. Licensed under the Apache License 2.0
  50. http://www.apache.org/licenses/LICENSE-2.0
  51. Distributed on an "AS IS" basis without warranties
  52. or conditions of any kind, either express or implied.
  53. USAGE
  54. ''' % (program_shortdesc, str(__date__))
  55. try:
  56. # Setup argument parser
  57. parser = ArgumentParser(description='Example Argparse Program', formatter_class=RawDescriptionHelpFormatter)
  58. parser.add_argument("filename", help="filename")
  59. parser.add_argument("-r", "--recursive", dest="recurse", action="store_true",
  60. help="recurse into subfolders [default: %(default)s]")
  61. parser.add_argument("-v", "--verbose", dest="verbose", action="count",
  62. help="set verbosity level [default: %(default)s]")
  63. parser.add_argument("-i", "--include", action="append", nargs='+',
  64. help="only include paths matching this regex pattern. Note: exclude is given preference over include. ",
  65. metavar="RE")
  66. parser.add_argument("-m", "--mycoolargument", help="mycoolargument")
  67. parser.add_argument("-e", "--exclude", dest="exclude",
  68. help="exclude paths matching this regex pattern. [default: %(default)s]", metavar="RE")
  69. parser.add_argument('-V', '--version', action='version')
  70. parser.add_argument('-T', '--tester', choices=['yes', 'no'])
  71. parser.add_argument(dest="paths", help="paths to folder(s) with source file(s) [default: %(default)s]",
  72. metavar="path", nargs='+')
  73. # for i in parser._actions:
  74. # print i
  75. # Process arguments
  76. args = parser.parse_args()
  77. paths = args.paths
  78. verbose = args.verbose
  79. recurse = args.recurse
  80. inpat = args.include
  81. expat = args.exclude
  82. if verbose > 0:
  83. print("Verbose mode on")
  84. if recurse:
  85. print("Recursive mode on")
  86. else:
  87. print("Recursive mode off")
  88. if inpat and expat and inpat == expat:
  89. raise CLIError("include and exclude pattern are equal! Nothing will be processed.")
  90. for inpath in paths:
  91. ### do something with inpath ###
  92. print(inpath)
  93. return 0
  94. except KeyboardInterrupt:
  95. ### handle keyboard interrupt ###
  96. return 0
  97. except Exception, e:
  98. if DEBUG or TESTRUN:
  99. raise (e)
  100. indent = len(program_name) * " "
  101. sys.stderr.write(program_name + ": " + repr(e) + "\n")
  102. sys.stderr.write(indent + " for help use --help")
  103. return 2
  104. if __name__ == "__main__":
  105. if DEBUG:
  106. sys.argv.append("-h")
  107. # sys.argv.append("-v")
  108. sys.argv.append("-r")
  109. main()
  110. sys.exit()
  111. if TESTRUN:
  112. import doctest
  113. doctest.testmod()
  114. if PROFILE:
  115. import cProfile
  116. import pstats
  117. profile_filename = 'bin.example_argparse_souce_profile.txt'
  118. cProfile.run('main()', profile_filename)
  119. statsfile = open("profile_stats.txt", "wb")
  120. p = pstats.Stats(profile_filename, stream=statsfile)
  121. stats = p.strip_dirs().sort_stats('cumulative')
  122. stats.print_stats()
  123. statsfile.close()
  124. sys.exit(0)
  125. sys.exit(main())