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.

173 lines
4.7 KiB

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