Browse Source

Updated examples

pull/61/head
chriskiehl 10 years ago
parent
commit
b0ccb94039
11 changed files with 460 additions and 5 deletions
  1. 2
      gooey/_tmp/example_argparse_souce_in_try.py
  2. 72
      gooey/_tmp/widget_demo.py
  3. 173
      gooey/examples/TODO.py
  4. 0
      gooey/examples/__init__.py
  5. 18
      gooey/examples/mock_argparse_example.py
  6. 51
      gooey/examples/mockapp_import_argparse.py
  7. 19
      gooey/examples/module_with_no_argparse.py
  8. 55
      gooey/examples/responding_to_error.py
  9. 67
      gooey/examples/widget_demo.py
  10. 2
      gooey/python_bindings/source_parser.py
  11. 6
      gooey/tests/source_parser_unittest.py

2
gooey/_tmp/example_argparse_souce_in_try.py

@ -55,7 +55,7 @@ class CLIError(Exception):
def main(argv=None): # IGNORE:C0111
'''Command line options.'''
raise NotImplementedError("This one isn't implemented yet. Please run any of the other examples. :) Sorry!")
if argv is None:
argv = sys.argv
else:

72
gooey/_tmp/widget_demo.py

@ -0,0 +1,72 @@
'''
Created on Dec 21, 2013
@author: Chris
'''
import sys
import hashlib
from time import time as _time, time
from time import sleep as _sleep
# from argparse import ArgumentParser
# import argparse
import argparse as ap
from argparse import ArgumentParser as AP
from gooey import Gooey
from gooey import GooeyParser
def main():
desc = "Example application to show Gooey's various widgets"
file_help_msg = "Name of the file you want to process"
my_cool_parser = GooeyParser(description=desc)
my_cool_parser.add_argument("filename", help=file_help_msg, widget="FileChooser") # positional
my_cool_parser.add_argument("directory", help="Directory to store output") # positional
my_cool_parser.add_argument('-c', '--countdown', default=2, type=int, help='sets the time to count down from you see its quite simple!')
my_cool_parser.add_argument('-j', '--cron-schedule', type=int, help='Set the datetime when the cron should begin', widget='DateChooser')
my_cool_parser.add_argument("-s", "--showtime", action="store_true", help="display the countdown timer")
my_cool_parser.add_argument("-d", "--delay", action="store_true", help="Delay execution for a bit")
my_cool_parser.add_argument('-v', '--verbose', action='count')
my_cool_parser.add_argument("-o", "--obfuscate", action="store_true", help="obfuscate the countdown timer!")
my_cool_parser.add_argument('-r', '--recursive', choices=['yes', 'no'], help='Recurse into subfolders')
my_cool_parser.add_argument("-w", "--writelog", default="No, NOT whatevs", help="write log to some file or something")
my_cool_parser.add_argument("-e", "--expandAll", action="store_true", help="expand all processes")
verbosity = my_cool_parser.add_mutually_exclusive_group()
verbosity.add_argument('-t', '--verbozze', dest='verbose', action="store_true", help="Show more details")
verbosity.add_argument('-q', '--quiet', dest='quiet', action="store_true", help="Only output on error")
print my_cool_parser._actions
print 'inside of main(), my_cool_parser =', my_cool_parser
args = my_cool_parser.parse_args()
print 'EHOOOOOOOOOOOO'
print sys.argv
print args.countdown
print args.showtime
start_time = _time()
print 'Counting down from %s' % args.countdown
while _time() - start_time < args.countdown:
if args.showtime:
print 'printing message at: %s' % _time()
else:
print 'printing message at: %s' % hashlib.md5(str(_time())).hexdigest()
_sleep(.5)
print 'Finished running the program. Byeeeeesss!'
raise ValueError("Something has gone wrong! AHHHHHHHHHHH")
def here_is_smore():
pass
if __name__ == '__main__':
print sys.argv
main()
# import inspect
# import dis
# # print dir(main.__code__)
# # for i in dir(main.__code__):
# # print i, getattr(main.__code__, i)
# print dis.dis(main.__code__)
# # for i in inspect.getmembers(main):
# # print i

173
gooey/examples/TODO.py

@ -0,0 +1,173 @@
#!/usr/local/bin/python2.7
# encoding: utf-8
'''
TODO: Fix this. Currently breaks parser
bin.example_argparse_souce -- shortdesc
bin.example_argparse_souce is a description
It defines classes_and_methods
@author: user_name
@copyright: 2013 organization_name. All rights reserved.
@license: license
@contact: user_email
@deffield updated: Updated
'''
import sys
import os
from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
from gooey.python_bindings.gooey_decorator import Gooey
__all__ = []
__version__ = 0.1
__date__ = '2013-12-13'
__updated__ = '2013-12-13'
DEBUG = 0
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
raise NotImplementedError("This one doesn't work just yet. Please run any of the other apps in the examples directory. :) Sorry!")
@Gooey
def main(argv=None): # IGNORE:C0111
'''Command line options.'''
if argv is None:
argv = sys.argv
else:
sys.argv.extend(argv)
program_name = os.path.basename(sys.argv[0])
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 = '''%s
Created by user_name on %s.
Copyright 2013 organization_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='Example Argparse Program', formatter_class=RawDescriptionHelpFormatter)
parser.add_argument("filename", help="filename")
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", action="append", nargs='+',
help="only include paths matching this regex pattern. Note: exclude is given preference over include. ",
metavar="RE")
parser.add_argument("-m", "--mycoolargument", help="mycoolargument")
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')
parser.add_argument('-T', '--tester', choices=['yes', 'no'])
parser.add_argument(dest="paths", help="paths to folder(s) with source file(s) [default: %(default)s]",
metavar="path", nargs='+')
# for i in parser._actions:
# print i
# Process arguments
args = parser.parse_args()
paths = args.paths
verbose = args.verbose
recurse = args.recurse
inpat = args.include
expat = args.exclude
if verbose > 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)
indent = len(program_name) * " "
sys.stderr.write(program_name + ": " + repr(e) + "\n")
sys.stderr.write(indent + " for help use --help")
return 2
if __name__ == "__main__":
if DEBUG:
sys.argv.append("-h")
# sys.argv.append("-v")
sys.argv.append("-r")
main()
sys.exit()
if TESTRUN:
import doctest
doctest.testmod()
if PROFILE:
import cProfile
import pstats
profile_filename = 'bin.example_argparse_souce_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')
stats.print_stats()
statsfile.close()
sys.exit(0)
sys.exit(main())

0
gooey/examples/__init__.py

18
gooey/examples/mock_argparse_example.py

@ -0,0 +1,18 @@
import argparse
from gooey import Gooey
@Gooey
def main():
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print args.accumulate(args.integers)
if __name__ == '__main__':
main()

51
gooey/examples/mockapp_import_argparse.py

@ -0,0 +1,51 @@
'''
Created on Dec 21, 2013
@author: Chris
'''
import sys
import hashlib
from time import time as _time
from time import sleep as _sleep
import argparse
from gooey import Gooey
@Gooey
def main():
my_cool_parser = argparse.ArgumentParser(description="Mock application to test Gooey's functionality")
my_cool_parser.add_argument("filename", help="Name of the file you want to read") # positional
my_cool_parser.add_argument("outfile", help="Name of the file where you'll save the output") # positional
my_cool_parser.add_argument('-c', '--countdown', default=10, type=int, help='sets the time to count down from')
my_cool_parser.add_argument("-s", "--showtime", action="store_true", help="display the countdown timer")
my_cool_parser.add_argument("-d", "--delay", action="store_true", help="Delay execution for a bit")
my_cool_parser.add_argument('--verbose', '-v', action='count')
my_cool_parser.add_argument("-o", "--obfuscate", action="store_true", help="obfuscate the countdown timer!")
my_cool_parser.add_argument('-r', '--recursive', choices=['yes', 'no'], help='Recurse into subfolders')
my_cool_parser.add_argument("-w", "--writelog", default="No, NOT whatevs", help="write log to some file or something")
my_cool_parser.add_argument("-e", "--expandAll", action="store_true", help="expand all processes")
print 'inside of main(), my_cool_parser =', my_cool_parser
args = my_cool_parser.parse_args()
print sys.argv
print args.countdown
print args.showtime
start_time = _time()
print 'Counting down from %s' % args.countdown
while _time() - start_time < args.countdown:
if args.showtime:
print 'printing message at: %s' % _time()
else:
print 'printing message at: %s' % hashlib.md5(str(_time())).hexdigest()
_sleep(.5)
print 'Finished running the program. Byeeeeesss!'
# raise ValueError("Something has gone wrong! AHHHHHHHHHHH")
if __name__ == '__main__':
# sys.argv.extend('asdf -c 5 -s'.split())
# print sys.argv
main()

19
gooey/examples/module_with_no_argparse.py

@ -0,0 +1,19 @@
'''
Created on Feb 2, 2014
@author: Chris
'''
import time
from gooey import Gooey
@Gooey
def main():
end = time.time() + 10
while end > time.time():
print 'Jello!', time.time()
time.sleep(.8)
if __name__ == '__main__':
main()

55
gooey/examples/responding_to_error.py

@ -0,0 +1,55 @@
'''
Created on Dec 21, 2013
@author: Chris
'''
import sys
import hashlib
from time import time as _time
from time import sleep as _sleep
from gooey import Gooey
from gooey import GooeyParser
@Gooey
def main():
desc = "Example application to show Gooey's various widgets"
my_cool_parser = GooeyParser(description=desc)
my_cool_parser.add_argument("Example", help="fill ", widget="FileChooser") # positional
verbosity = my_cool_parser.add_mutually_exclusive_group()
verbosity.add_argument('-t', '--verbozze', dest='verbose', action="store_true", help="Show more details")
verbosity.add_argument('-q', '--quiet', dest='quiet', action="store_true", help="Only output on error")
print my_cool_parser._actions
print 'inside of main(), my_cool_parser =', my_cool_parser
args = my_cool_parser.parse_args()
print sys.argv
print args.countdown
print args.showtime
start_time = _time()
print 'Counting down from %s' % args.countdown
while _time() - start_time < args.countdown:
if args.showtime:
print 'printing message at: %s' % _time()
else:
print 'printing message at: %s' % hashlib.md5(str(_time())).hexdigest()
_sleep(.5)
print 'Finished running the program. Byeeeeesss!'
def here_is_smore():
pass
if __name__ == '__main__':
print sys.argv
main()
# import inspect
# import dis
# # print dir(main.__code__)
# # for i in dir(main.__code__):
# # print i, getattr(main.__code__, i)
# print dis.dis(main.__code__)
# # for i in inspect.getmembers(main):
# # print i

67
gooey/examples/widget_demo.py

@ -0,0 +1,67 @@
'''
Created on Dec 21, 2013
@author: Chris
'''
import sys
import hashlib
from time import time as _time
from time import sleep as _sleep
from gooey import Gooey
from gooey import GooeyParser
@Gooey
def main():
desc = "Example application to show Gooey's various widgets"
file_help_msg = "Name of the file you want to process"
my_cool_parser = GooeyParser(description=desc)
my_cool_parser.add_argument("filename", help=file_help_msg, widget="FileChooser") # positional
my_cool_parser.add_argument("directory", help="Directory to store output") # positional
my_cool_parser.add_argument('-c', '--countdown', default=2, type=int, help='sets the time to count down from you see its quite simple!')
my_cool_parser.add_argument('-j', '--cron-schedule', type=int, help='Set the datetime when the cron should begin', widget='DateChooser')
my_cool_parser.add_argument("-s", "--showtime", action="store_true", help="display the countdown timer")
my_cool_parser.add_argument("-d", "--delay", action="store_true", help="Delay execution for a bit")
my_cool_parser.add_argument('-v', '--verbose', action='count')
my_cool_parser.add_argument("-o", "--obfuscate", action="store_true", help="obfuscate the countdown timer!")
my_cool_parser.add_argument('-r', '--recursive', choices=['yes', 'no'], help='Recurse into subfolders')
my_cool_parser.add_argument("-w", "--writelog", default="No, NOT whatevs", help="write log to some file or something")
my_cool_parser.add_argument("-e", "--expandAll", action="store_true", help="expand all processes")
verbosity = my_cool_parser.add_mutually_exclusive_group()
verbosity.add_argument('-t', '--verbozze', dest='verbose', action="store_true", help="Show more details")
verbosity.add_argument('-q', '--quiet', dest='quiet', action="store_true", help="Only output on error")
print my_cool_parser._actions
print 'inside of main(), my_cool_parser =', my_cool_parser
args = my_cool_parser.parse_args()
print sys.argv
print args.countdown
print args.showtime
start_time = _time()
print 'Counting down from %s' % args.countdown
while _time() - start_time < args.countdown:
if args.showtime:
print 'printing message at: %s' % _time()
else:
print 'printing message at: %s' % hashlib.md5(str(_time())).hexdigest()
_sleep(.5)
print 'Finished running the program. Byeeeeesss!'
def here_is_smore():
pass
if __name__ == '__main__':
print sys.argv
main()
# import inspect
# import dis
# # print dir(main.__code__)
# # for i in dir(main.__code__):
# # print i, getattr(main.__code__, i)
# print dis.dis(main.__code__)
# # for i in inspect.getmembers(main):
# # print i

2
gooey/python_bindings/source_parser.py

@ -148,7 +148,7 @@ def extract_parser(modulepath):
if __name__ == '__main__':
filepath = os.path.join(os.path.dirname(__file__),
'mockapplications',
'examples',
'example_argparse_souce_in_main.py')
nodes = ast.parse(_openfile(filepath))

6
gooey/tests/source_parser_unittest.py

@ -49,15 +49,15 @@ if __name__ == '__main__':
class TestSourceParser(unittest.TestCase):
PATH = os.path.join(os.path.dirname(__file__), 'mockapplications')
PATH = os.path.join(os.path.dirname(__file__), 'examples')
def module_path(self, name):
return os.path.join(self.PATH, name)
def setUp(self):
self._mockapp = self.module_path('mockapplications.py')
self._mockapp = self.module_path('examples.py')
self._module_with_noargparse = self.module_path('module_with_no_argparse.py')
self._module_with_arparse_in_try = self.module_path('example_argparse_souce_in_try.py')
self._module_with_arparse_in_try = self.module_path('TODO.py')
self._module_with_argparse_in_main = self.module_path('example_argparse_souce_in_main.py')
def test_should_throw_parser_exception_if_no_argparse_found_in_module(self):

Loading…
Cancel
Save