def parse_options(): """ Parse command line options """ import version formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [options]", version='%prog ' + str(version.version)) parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0] parser.description = "Convert station list (TV_CHANNELS) from local_conf.py for tvtime" parser.add_option( '--band', choices=bands, default=bands[0], metavar='BAND', help='Select the TV band [default:%default], choose from: "' + '", "'.join(bands) + '"') opts, args = parser.parse_args() return opts, args
def _proc_evt_abort(cmd, args): """Abort TARGETS of given type. If TARGETS are not given, aborts current task/recipe/recipeset as specified by environment.""" global abort_opts cmd = cmd.lower() abort_type = cmd[len('abort'):] if abort_type.startswith('_'): abort_type = abort_type[1:] abort_type = {'r':'recipe', 'rs':'recipeset', 't':'task'}.get(abort_type, abort_type) if not abort_opts: abort_opts = OptionParser(usage="%prog [OPTIONS] [TARGETS]", description="Return a %prog result.") abort_opts.disable_interspersed_args() abort_opts.add_option("-m", "--message", action="store", dest="message", help="message to log", type="string", default="") abort_opts.prog = cmd opts, args = abort_opts.parse_args(args) if args: targets = args else: abort_env = {'task':'TASKID', 'recipe':'RECIPEID', 'recipeset':'RECIPESET'}[abort_type] target = os.getenv(abort_env) if target: targets = [target] else: targets = [] evts = [] for target in targets: evts.append(event.abort(abort_type, target=target, message=opts.message)) return evts
def main(argv): # Create an OptionParser for reading optional parameters parser = OptionParser(version='0.10') parser.prog = 'Model Runner Plots Test' print 'Running ' + parser.prog + ' ' + parser.version options, args = parser.parse_args(argv) log = False # Use a hardcoded value for the input filename, probably adding in an option argument later # for more flexibility filename = 'output_test/BigHorn_Temperature.txt' # Create the data frames and plots from the input file (df, df_closest_fit) = ModelRunnerPlots.create_dataframes(filename, log) # Get the plot and create a matplotlib figure. df_plot = ModelRunnerPlots.create_line_plot('Temperature', 'Temperature in Farenheit', df=df, log=log, value_vars=list(df.columns - ['year'])) df_plot.savefig('graph_test.png', format='png') # Create our GUI componenets. Note, the data frame and plot must be created beforehand for the GUI to work properly. root = Tkinter.Tk() root.title(parser.prog + ' ' + parser.version) root.grid() model_runner_gui = ModelRunnerGraphGUI.GraphFrame(root, df=df, plot=df_plot) model_runner_gui.set_grid() # Run the window main loop root.mainloop()
def _proc_evt_log(cmd, args): """Return a log event.""" global log_opts cmd = cmd.lower() text_level = { 'log': 'linfo', 'ldebug': 'ldebug1', 'lwarn': 'lwarning', 'INFO': 'linfo', 'ERR': 'lerror', 'WARN': 'lwarning', 'DEBUG': 'ldebug1' }.get(cmd, cmd) log_level = __TEXT_LOG_LEVEL_TO_BEAH.get(text_level) if not log_opts: log_opts = OptionParser(usage="%prog [OPTIONS] MESSAGE", description="Return a %prog log event.") log_opts.disable_interspersed_args() log_opts.add_option("-H", "--handle", action="store", dest="handle", help="log handle", type="string", default="") log_opts.prog = text_level opts, args = log_opts.parse_args(args) return [ event.log(message=" ".join(args), log_level=log_level, log_handle=opts.handle) ]
def parse_options(): """ Parse command line options """ import version formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [options]", version='%prog ' + str(version.version)) prog = os.path.basename(sys.argv[0]) parser.prog = os.path.splitext(prog)[0] parser.description = "Downloads the listing for xmltv and cache the data" parser.add_option( '-u', '--update', action='store_true', default=False, help= 'Update the database only, do not attempt to retrieve listings. [default:%default]' ) opts, args = parser.parse_args() return opts, args
def parse_options(): """ Parse command line options """ import version formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser( conflict_handler="resolve", formatter=formatter, usage="freevo %prog [options]", version="%prog " + str(version.version), ) parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0] parser.description = "Helper to convert old local_conf.py configuration to current configuration" # parser.add_option('-v', '--verbose', action='count', default=0, # help='set the level of verbosity [default:%default]') parser.add_option("--scan", action="store_true", default=False, help="scan source files for the old variables") parser.add_option("--file", metavar="FILE", default=None, help="the local_conf.py file [default:%default]") parser.add_option( "-w", "--write", action="store_true", default=False, help="write the local_conf.py file, this will overwrite an existing file!", ) opts, args = parser.parse_args() if not opts.file and not opts.scan: parser.error("either --scan or --file must be given.") return opts, args
def parse_options(): """ Parse command line options """ import version formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [options]", version='%prog ' + str(version.version)) parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0] parser.description = "Helper to convert the record_schedule.xml to favorites.pickle" parser.add_option('-v', '--verbose', action='count', default=0, help='set the level of verbosity [default:%default]') parser.add_option('-i', '--schedule', metavar='FILE', default=config.TV_RECORD_SCHEDULE, help='the record schedule file [default:%default]') parser.add_option('-o', '--favorites', metavar='FILE', default=config.TV_RECORD_FAVORITES, help='the record favorites file [default:%default]') opts, args = parser.parse_args() if not os.path.exists(opts.schedule): parser.error('%r does not exist.' % (opts.schedule,)) if os.path.exists(opts.favorites): parser.error('%r exists, please remove.' % (opts.favorites,)) if os.path.splitext(opts.schedule)[1] != '.xml': parser.error('%r is not an XML file.' % (opts.schedule,)) return opts, args
def _proc_evt_result(cmd, args): """Return a result.""" global result_opts cmd = cmd.lower() text_result = {'warning':'warn', 'error':'fail'}.get(cmd, cmd) evt_result = __TEXT_RESULT_TO_BEAH.get(text_result[:4]) if not result_opts: result_opts = OptionParser(usage="%prog [OPTIONS] MESSAGE", description="Return a %prog result.") result_opts.disable_interspersed_args() result_opts.add_option("-H", "--handle", action="store", dest="handle", help="result handle", type="string", default="") result_opts.add_option("-s", "--score", action="store", dest="score", help="result score", default="0.0", type="float") result_opts.add_option("-f", "--file", action="append", dest="files", help="Attach a file.") result_opts.prog = text_result opts, args = result_opts.parse_args(args) statistics = {} if opts.score: statistics["score"] = opts.score s = AppendingSender() r = beahlib.get_task(s).result(evt_result, handle=opts.handle, message=" ".join(args), statistics=statistics) attach(r, opts.files) return s.get_events()
def parse_options(): """ Parse command line options """ import version tmp = os.environ.has_key('TEMP') and os.environ['TEMP'] or '/tmp' formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [options]", version='%prog ' + str(version.version)) parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0] parser.description = "Helper to convert a favorites.txt to a favorites.pickle" parser.add_option('-v', '--verbose', action='count', default=0, help='set the level of verbosity [default:%default]') parser.add_option('--favorites-txt', metavar='FILE', default=config.TV_RECORD_FAVORITES_LIST, help='the favorites.txt file to read and process [default:%default]') parser.add_option('--favorites-pickle-out', metavar='FILE', default=os.path.join(tmp, 'favorites.pickle'), help='the reritten favorites.pickle file [default:%default]') parser.add_option('--favorites-txt-out', metavar='FILE', default=os.path.join(tmp, 'favorites.txt'), help='the reritten favorites.txt file [default:%default]') parser.add_option('--schedule-pickle-out', metavar='FILE', default=os.path.join(tmp, 'schedule.pickle'), help='the reritten schedule.pickle file [default:%default]') opts, args = parser.parse_args() return opts, args
def cmdline(self, argv=None): '''Supported commands: psync list psync show <sync> psync a <sync> <path>... psync b <sync> <path>... ''' from optparse import OptionParser op = OptionParser('%prog [options] method [arg..]') op.add_option('--config','-c', help='alternative to ~/.psync') op.add_option('--debug','-d', action='store_true', help='Debug logging') if argv is not None: op.prog = argv[0] argv = argv[1:] opts, args = op.parse_args(argv) if opts.debug: logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) inifile = opts.config if inifile is None: inifile = os.path.expanduser('~/.psync') self.read_inifile(inifile) # Process arguments if len(args) < 1: op.error('No command') else: try: self.do_cmd(args[0], args[1:], opts) except UsageError, e: op.error('Error in %s command: %s' % (args[0], e.args[0])) except CmdError, e: op.error(e.args[0])
def main(): '''Parse command-line arguments and start up the simulation''' parser = OptionParser() parser.prog = "fs.py" parser.add_option("-f", "--logfile", dest="logfile", default="", help="Send log to file (default: log to stderr)") parser.add_option("-d", "--debug", dest="debug", default=0, action="count", help="Turn on debugging output (may be given multiple times to increase debug output)") parser.add_option("-t", "--simtime", dest="simtime", default=300, type=int, help="Set amount of simulation time (default: 300 sec)") parser.add_option("-i", "--interval", dest="interval", default=1.0, type=float, help="Set the simulation tick interval (sec) (default: 1 sec)") parser.add_option("-c", "--configonly", dest="configonly", default=False, action="store_true", help="Just do configuration then exit") parser.add_option("-s", "--seed", dest="seed", default=None, type="int", help="Set random number generation seed (default: seed based on system time)") (options, args) = parser.parse_args() if len(args) != 1: print >> sys.stderr,"Usage: %s [options] <scenario.[dot,json]>" % (sys.argv[0]) sys.exit(0) random.seed(options.seed) fscommon.setup_logger(options.logfile, options.debug) sim = FsCore(options.interval, endtime=options.simtime, debug=options.debug) signal.signal(signal.SIGINT, sim.sighandler) sys.path.append(".") sim.run(args[0], configonly=options.configonly)
def parse_options(): """ Parse command line options """ conf = FreevoConf() formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="""freevo %prog [options] For more information see: freevo %prog -- --help""", version='%prog ' + str(conf.version)) parser.prog = 'setup' parser.description = """Set up Freevo for your specific environment. Depending on the display and the tv standard the geometry may be automatically changed.""" parser.add_option('-v', '--verbose', action='count', default=0, help='set the level of verbosity [default:%default]') parser.add_option('--geometry', default=conf.geometry, metavar='GEOMETRY', help='set the screen geometry as "WIDTHxHEIGHT" [default:%default]') parser.add_option('--position', default=conf.position, metavar='POSITION', help='set the screen position as "X,Y" [default:%default]') parser.add_option('--display', choices=conf.displays, default=conf.display, metavar='DISPLAY', help='set the display [default:%default], choose from: "' + '", "'.join(conf.displays) + '"') parser.add_option('--tv', choices=conf.tv_norms, default=conf.tv, metavar='STANDARD', help='set the TV standard [default:%default], choose from: "' + '", "'.join(conf.tv_norms) + '"') parser.add_option('--chanlist', choices=conf.chanlists, default=conf.chanlist, metavar='LIST', help='set the channel list [default:%default], choose from: "' + '", "'.join(conf.chanlists) + '"') parser.add_option('--sysfirst', action='store_true', default=False, help='search for programs from system path first [default:%default]') parser.add_option('--compile', action='store', default=None, help='compile the modules [default:%default]') parser.add_option('--prefix', action='store', default='.', help='destination prefix the modules [default:%default]') opts, args = parser.parse_args() try: w, h = opts.geometry.split('x') w = int(w) h = int(h) except: parser.error('geometry %r is not "<width>x<height>"' % opts.geometry) try: x, y = opts.position.split(',') x = int(x) y = int(y) except: parser.error('position %r is not "<x>x<y>"' % opts.geometry) if opts.compile is not None: try: c = int(opts.compile) if c < 0 or c > 2: raise ValueError('value is < 0 or > 2') except ValueError, why: parser.error('compile %r: %s' % opts.geometry)
def main(): usage = "%prog DIR1 DIR2 ... -l LICENSE [OPTIONS]" parser = OptionParser(usage) parser.prog = "addlicense" parser.version = "0.1" parser.description = "Add license header to all the files in the \ specified directories (and their sub-directories). If no directory is \ specified, the current working directory will be considered. \ Insert license headers for Java and PHP files, based on the file \ extension. Supported licenses are: Apache v2, GPL v3" parser.add_option("-e", "--exclude", dest="exclude", \ help="exclude all files in DIR and sub-DIRs", \ metavar="DIR", action="append") parser.add_option("-f", "--file", dest="file", help="include FILE, has to be an absolute path", metavar="FILE", action="append") parser.add_option("-l", "--license", dest="license", \ help="add LICENSE header; accepted LICENSEs are: \ 'apache2', 'gpl3'" , \ action="store", metavar="LICENSE") parser.add_option("-y", "--year", metavar="YEAR", dest="year", \ help="use YEAR as the license year; default \ is the current year" , \ action="store") parser.add_option("-r", "--holder", metavar="HOLDER", dest="holder", \ action="store", \ help="use HOLDER as the copyright's holder") parser.add_option("-m", "--email", metavar="EMAIL", dest="holder_email", \ action="store", \ help="use EMAIL as the email of the copyright's holder") parser.add_option("-v", "--verbose", dest="verbose", action="store_true", \ help="be verbose", default=False) (options, args) = parser.parse_args() if len(args) == 0 and (options.license == None or options.license not in valid_licenses): print "Usage: addlicense DIR1 DIR2 ... -l LICENSE [OPTIONS]\n" print "Type 'addlicense -h' for more information." exit(2) # if no directory is specified, add the current one if len(args) == 0 and options.file == None: args.append(os.getcwd()) if len(args) > 0: _check_args(args) _check_options(options) crawldirs.crawl(args, cmd_options, excluded_dirs, included_files)
def proc_evt_upload(cmd, args): """Upload a file.""" global upload_opts if not upload_opts: upload_opts = OptionParser(usage="%prog FILES", description="Attach FILES to the current task.") upload_opts.prog = "upload" opts, args = upload_opts.parse_args(args) s = AppendingSender() t = beahlib.get_task(s) attach(t, args) return s.get_events()
def parse_options(): """ Parse command line options """ import version formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [--daemon|--stop]", version='%prog ' + str(version.version)) parser.prog = appname parser.description = "start or stop the internal webserver" opts, args = parser.parse_args() return opts, args
def main(): parser = OptionParser() parser.prog = "fsconfgen.py" parser.add_option("-n", "--name", dest="name", default="myfs", help="Set the name of the generated configuration.") (options, args) = parser.parse_args() cfg = base_config(options.name) namea, idxa = make_node(cfg, addtraffic=True) nameb, idxb = make_node(cfg, addtraffic=False) make_link(cfg, namea, nameb) write_config(cfg, "test.json")
def proc_evt_upload(cmd, args): """Upload a file.""" global upload_opts if not upload_opts: upload_opts = OptionParser( usage="%prog FILES", description="Attach FILES to the current task.") upload_opts.prog = "upload" opts, args = upload_opts.parse_args(args) s = AppendingSender() t = beahlib.get_task(s) attach(t, args) return s.get_events()
def parse_options(): """ Parse command line options """ import version formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [options]", version='%prog ' + str(version.version)) parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0] parser.description = "release the vt in case freevo crashed and still locks the framebuffer" opts, args = parser.parse_args() return opts, args
def main(): parser = OptionParser() parser.prog = "flowmax.py" parser.add_option("-x", "--debug", dest="debug", default=False, action="store_true", help="Turn on debugging output") parser.add_option("-t", "--simtime", dest="simtime", default=300, type=int, help="Set amount of simulation time; default=300 sec") parser.add_option("-i", "--interval", dest="interval", default=1.0, type=float, help="Set the simulation tick interval (sec); default=1 sec") parser.add_option("-s", "--snmpinterval", dest="snmpinterval", default=0.0, type=float, help="Set the interval for dumping SNMP-like counters at each router (specify non-zero value to dump counters); default=no dump") parser.add_option("-S", "--snmpexportfile", dest="snmpexportfile", default=None, help="Specify file for dumping SNMP-like counters (or 'stdout'); no default") parser.add_option("-e", "--exporter", dest="exporter", default="text", help="Set the export type (text,cflow); default=text") parser.add_option("-z", "--usepsyco", action="store_true", default=False, help="Use psyco for performance improvement; default=no psyco") (options, args) = parser.parse_args() if len(args) != 1: print >>sys.stderr,"Usage: %s [options] <scenario.dot>" % (sys.argv[0]) sys.exit(0) scenario = args[0] exporter = None if options.exporter == 'text': exporter = text_export_factory elif options.exporter == 'cflow': exporter = cflowd_export_factory elif options.exporter == 'null': exporter = null_export_factory else: print >>sys.stderr, "Invalid export type. Need 'text' or 'cflow'" sys.exit(0) sim = Simulator(options.interval, scenario, exporter, endtime=options.simtime, debug=options.debug, snmpexportinterval=options.snmpinterval, snmpexportfile=options.snmpexportfile) signal.signal(signal.SIGINT, sim.sighandler) if options.usepsyco: try: import psyco print >>sys.stderr, 'Starting psyco' # psyco.log() # psyco.profile(0.01) psyco.full() print >>sys.stderr, 'Done starting psyco' except ImportError: print >>sys.stderr, 'Sorry, no psyco' sim.run()
def main(): usage = "%prog DIR1 DIR2 ... -l LICENSE [OPTIONS]" parser = OptionParser(usage) parser.prog = "addlicense" parser.version = "0.1" parser.description = "Add license header to all the files in the \ specified directories (and their sub-directories). If no directory is \ specified, the current working directory will be considered. \ Insert license headers for Java and PHP files, based on the file \ extension. Supported licenses are: Apache v2, GPL v3" parser.add_option("-e", "--exclude", dest="exclude", \ help="exclude all files in DIR and sub-DIRs", \ metavar="DIR", action="append") parser.add_option("-f", "--file", dest="file", help="include FILE, has to be an absolute path", metavar="FILE", action="append") parser.add_option("-l", "--license", dest="license", \ help="add LICENSE header; accepted LICENSEs are: \ 'apache2', 'gpl3'", \ action="store", metavar="LICENSE") parser.add_option("-y", "--year", metavar="YEAR", dest="year", \ help="use YEAR as the license year; default \ is the current year", \ action="store") parser.add_option("-r", "--holder", metavar="HOLDER", dest="holder", \ action="store", \ help="use HOLDER as the copyright's holder") parser.add_option("-m", "--email", metavar="EMAIL", dest="holder_email", \ action="store", \ help="use EMAIL as the email of the copyright's holder") parser.add_option("-v", "--verbose", dest="verbose", action="store_true", \ help="be verbose", default=False) (options, args) = parser.parse_args() if len(args) == 0 and (options.license == None or options.license not in valid_licenses): print "Usage: addlicense DIR1 DIR2 ... -l LICENSE [OPTIONS]\n" print "Type 'addlicense -h' for more information." exit(2) # if no directory is specified, add the current one if len(args) == 0 and options.file == None: args.append(os.getcwd()) if len(args) > 0: _check_args(args) _check_options(options) crawldirs.crawl(args, cmd_options, excluded_dirs, included_files)
def parse_options(): """ Parse command line options """ import version formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [options]", version='%prog ' + str(version.version)) parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0] parser.description = "Convert station list (TV_CHANNELS) from local_conf.py for tvtime" parser.add_option('--band', choices=bands, default=bands[0], metavar='BAND', help='Select the TV band [default:%default], choose from: "' + '", "'.join(bands) + '"') opts, args = parser.parse_args() return opts, args
def parse_options(): """ Parse command line options """ import version formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [--daemon|--stop]", version='%prog ' + str(version.version)) parser.prog = appname parser.description = "start or stop the commercial detection server" parser.add_option('-d', '--debug', action='store_true', dest='debug', default=False, help='enable debugging') opts, args = parser.parse_args() return opts, args
def parse_options(): """ Parse command line options """ import version formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [options]", version='%prog ' + str(version.version)) prog = os.path.basename(sys.argv[0]) parser.prog = os.path.splitext(prog)[0] parser.description = "Downloads the listing for xmltv and cache the data" parser.add_option('-u', '--update', action='store_true', default=False, help='Update the database only, do not attempt to retrieve listings. [default:%default]') opts, args = parser.parse_args() return opts, args
def _proc_evt_abort(cmd, args): """Abort TARGETS of given type. If TARGETS are not given, aborts current task/recipe/recipeset as specified by environment.""" global abort_opts cmd = cmd.lower() abort_type = cmd[len('abort'):] if abort_type.startswith('_'): abort_type = abort_type[1:] abort_type = { 'r': 'recipe', 'rs': 'recipeset', 't': 'task' }.get(abort_type, abort_type) if not abort_opts: abort_opts = OptionParser(usage="%prog [OPTIONS] [TARGETS]", description="Return a %prog result.") abort_opts.disable_interspersed_args() abort_opts.add_option("-m", "--message", action="store", dest="message", help="message to log", type="string", default="") abort_opts.prog = cmd opts, args = abort_opts.parse_args(args) if args: targets = args else: abort_env = { 'task': 'TASKID', 'recipe': 'RECIPEID', 'recipeset': 'RECIPESET' }[abort_type] target = os.getenv(abort_env) if target: targets = [target] else: targets = [] evts = [] for target in targets: evts.append( event.abort(abort_type, target=target, message=opts.message)) return evts
def parse_options(): """ Parse command line options """ import version formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [options]", version='%prog ' + str(version.version)) parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0] parser.description = "Helper to convert the record_schedule.xml to favorites.pickle" parser.add_option('-v', '--verbose', action='count', default=0, help='set the level of verbosity [default:%default]') parser.add_option('-i', '--schedule', metavar='FILE', default=config.TV_RECORD_SCHEDULE, help='the record schedule file [default:%default]') parser.add_option('-o', '--favorites', metavar='FILE', default=config.TV_RECORD_FAVORITES, help='the record favorites file [default:%default]') opts, args = parser.parse_args() if not os.path.exists(opts.schedule): parser.error('%r does not exist.' % (opts.schedule, )) if os.path.exists(opts.favorites): parser.error('%r exists, please remove.' % (opts.favorites, )) if os.path.splitext(opts.schedule)[1] != '.xml': parser.error('%r is not an XML file.' % (opts.schedule, )) return opts, args
def _proc_evt_log(cmd, args): """Return a log event.""" global log_opts cmd = cmd.lower() text_level = {'log':'linfo', 'ldebug':'ldebug1', 'lwarn':'lwarning', 'INFO':'linfo', 'ERR':'lerror', 'WARN':'lwarning', 'DEBUG':'ldebug1'}.get(cmd, cmd) log_level = __TEXT_LOG_LEVEL_TO_BEAH.get(text_level) if not log_opts: log_opts = OptionParser(usage="%prog [OPTIONS] MESSAGE", description="Return a %prog log event.") log_opts.disable_interspersed_args() log_opts.add_option("-H", "--handle", action="store", dest="handle", help="log handle", type="string", default="") log_opts.prog = text_level opts, args = log_opts.parse_args(args) return [event.log(message=" ".join(args), log_level=log_level, log_handle=opts.handle)]
def parse_options(): """ Parse command line options """ import version formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [options]", version='%prog ' + str(version.version)) parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0] parser.description = "Parse the input header file for event data" parser.add_option('-v', '--verbose', action='count', default=0, help='set the level of verbosity [default:%default]') parser.add_option('--device', metavar='DEVICE', default='/dev/input/event0', help='device [default:%default] information will be also written to stdout') parser.add_option('--input', metavar='INPUT', default='/usr/include/linux/input.h', help='parse the imput header [default:%default] and write the event' \ 'data to stdout, this can be redirected to the linuxevent.py') opts, args = parser.parse_args() return opts, args
def _proc_evt_result(cmd, args): """Return a result.""" global result_opts cmd = cmd.lower() text_result = {'warning': 'warn', 'error': 'fail'}.get(cmd, cmd) evt_result = __TEXT_RESULT_TO_BEAH.get(text_result[:4]) if not result_opts: result_opts = OptionParser(usage="%prog [OPTIONS] MESSAGE", description="Return a %prog result.") result_opts.disable_interspersed_args() result_opts.add_option("-H", "--handle", action="store", dest="handle", help="result handle", type="string", default="") result_opts.add_option("-s", "--score", action="store", dest="score", help="result score", default="0.0", type="float") result_opts.add_option("-f", "--file", action="append", dest="files", help="Attach a file.") result_opts.prog = text_result opts, args = result_opts.parse_args(args) statistics = {} if opts.score: statistics["score"] = opts.score s = AppendingSender() r = beahlib.get_task(s).result(evt_result, handle=opts.handle, message=" ".join(args), statistics=statistics) attach(r, opts.files) return s.get_events()
def parse_options(): """ Parse command line options """ import version formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [options] [BUTTON=EVENT]", version='%prog ' + str(version.version)) parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0] parser.description = "Helper to write the freevo lircrc file" parser.add_option('-v', '--verbose', action='count', default=0, help='set the level of verbosity [default:%default]') parser.add_option('--lircrc', metavar='FILE', default=config.LIRCRC, help='the lircrc file [default:%default]') parser.add_option( '-r', '--remote', metavar='NAME', default=None, help='the name of the remote in the lircrc file [default:%default]') parser.add_option( '-w', '--write', action='store_true', default=False, help='write the lircrc file, this will overwrite an existing file!') opts, args = parser.parse_args() return opts, args
def parse_options(): """ Parse command line options """ import version formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [options] [BUTTON=EVENT]", version='%prog ' + str(version.version)) parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0] parser.description = "Helper to write the freevo lircrc file" parser.add_option('-v', '--verbose', action='count', default=0, help='set the level of verbosity [default:%default]') parser.add_option('--lircrc', metavar='FILE', default=config.LIRCRC, help='the lircrc file [default:%default]') parser.add_option('-r', '--remote', metavar='NAME', default=None, help='the name of the remote in the lircrc file [default:%default]') parser.add_option('-w', '--write', action='store_true', default=False, help='write the lircrc file, this will overwrite an existing file!') opts, args = parser.parse_args() return opts, args
def parse_options(): """ Parse command line options """ import version formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="freevo %prog [options]", version='%prog ' + str(version.version)) parser.prog = os.path.splitext(os.path.basename(sys.argv[0]))[0] parser.description = "Helper to convert old local_conf.py configuration to current configuration" #parser.add_option('-v', '--verbose', action='count', default=0, # help='set the level of verbosity [default:%default]') parser.add_option('--scan', action='store_true', default=False, help='scan source files for the old variables') parser.add_option('--file', metavar='FILE', default=None, help='the local_conf.py file [default:%default]') parser.add_option( '-w', '--write', action='store_true', default=False, help= 'write the local_conf.py file, this will overwrite an existing file!') opts, args = parser.parse_args() if not opts.file and not opts.scan: parser.error('either --scan or --file must be given.') return opts, args
def _func_to_option_parser(func): args, varargs, kwargs, defaults = inspect.getargspec(func) defaults = defaults or () options = dict(zip(args[-len(defaults):], defaults)) required_args = args[:] if defaults: required_args = args[:-len(defaults)] parser = OptionParser(usage=func.__doc__) parser.prog = func.__name__ short_names = set(['h']) for arg_name, default in options.items(): lower, upper = list(arg_name), list(arg_name.upper()) short_chars = reduce(lambda a, b: a + list(b), zip(lower, upper), []) short_chars = [c for c in short_chars if c not in short_names] if short_chars: short_name = short_chars[0] else: sort_name = arg_name[0] short_names.add(short_name) arg_type = 'string' if type(default) == int: arg_type = 'int' elif type(default) == float: arg_type = 'float' if default in (True, False, bool): action = 'store_true' arg_type = None else: action = 'store' short_name = '-' + short_name long_name = '--' + arg_name.replace('_', '-') parser.add_option(short_name, long_name, action=action, dest=arg_name, default=default, type=arg_type) return parser, required_args
Make an easy web interface for tracking what you're eating, when, how much. Nice easy mobile-friendly data entry form. """ from datetime import date, datetime, timedelta from optparse import OptionParser from django.conf import settings from django.db import models from tagging.models import Tag from tagging.fields import TagField swallop = OptionParser() swallop.prog = 'swallo' swallop.usage = '%prog [options]' swallop.add_option("-a", "--amt", dest="amount",) swallop.add_option("-c", "--cal", dest="calories") swallop.add_option("-t", "--tag", dest="tags") swallop.add_option("-m", "--memo", dest="description") weighp = OptionParser() weighp.add_option("-e", "--empty", dest="empty") weighp.add_option("-m", "--memo", dest="description") entry_help_text = swallop.usage ENTRY_HELP_TEXT = "swallo ITEM [-a/--amt '3 biscuits'][-c/--cal 240][-t/--tag bkfst][-m]<br/>" \ "weigh 150lb [-e/--empty]<br/>" \ "woke 1015 [-m]<br/>" \
def parse_options(): """ Parse command line options """ conf = FreevoConf() formatter = IndentedHelpFormatter(indent_increment=2, max_help_position=32, width=100, short_first=0) parser = OptionParser(conflict_handler='resolve', formatter=formatter, usage="""freevo %prog [options] For more information see: freevo %prog -- --help""", version='%prog ' + str(conf.version)) parser.prog = 'setup' parser.description = """Set up Freevo for your specific environment. Depending on the display and the tv standard the geometry may be automatically changed.""" parser.add_option('-v', '--verbose', action='count', default=0, help='set the level of verbosity [default:%default]') parser.add_option( '--geometry', default=conf.geometry, metavar='GEOMETRY', help='set the screen geometry as "WIDTHxHEIGHT" [default:%default]') parser.add_option( '--position', default=conf.position, metavar='POSITION', help='set the screen position as "X,Y" [default:%default]') parser.add_option( '--display', choices=conf.displays, default=conf.display, metavar='DISPLAY', help='set the display [default:%default], choose from: "' + '", "'.join(conf.displays) + '"') parser.add_option( '--tv', choices=conf.tv_norms, default=conf.tv, metavar='STANDARD', help='set the TV standard [default:%default], choose from: "' + '", "'.join(conf.tv_norms) + '"') parser.add_option( '--chanlist', choices=conf.chanlists, default=conf.chanlist, metavar='LIST', help='set the channel list [default:%default], choose from: "' + '", "'.join(conf.chanlists) + '"') parser.add_option( '--sysfirst', action='store_true', default=False, help='search for programs from system path first [default:%default]') parser.add_option('--compile', action='store', default=None, help='compile the modules [default:%default]') parser.add_option('--prefix', action='store', default='.', help='destination prefix the modules [default:%default]') opts, args = parser.parse_args() try: w, h = opts.geometry.split('x') w = int(w) h = int(h) except: parser.error('geometry %r is not "<width>x<height>"' % opts.geometry) try: x, y = opts.position.split(',') x = int(x) y = int(y) except: parser.error('position %r is not "<x>x<y>"' % opts.geometry) if opts.compile is not None: try: c = int(opts.compile) if c < 0 or c > 2: raise ValueError('value is < 0 or > 2') except ValueError, why: parser.error('compile %r: %s' % opts.geometry)
def process_cmd_line(): """ Processes the command line arguments and sets up the system control variables accordingly. If an error occurred, an error message indicating the fault will be printed before the returning False. :return Returns options if no errors occurred, otherwise False. """ # Set up parser opt_parser = OptionParser() opt_parser.prog = "direcMeasure" usage = set_usage(opt_parser.prog) opt_parser.set_usage(usage) opt_parser.set_defaults(run_type="f", verbose=False) # Main options opt_parser.add_option( "-c", "--config", type="string", action="store", dest="cfg", default='', help= "Configuration file used to control the system. Must be a JSON file.") opt_parser.add_option("-a", "--alignOnly", action="callback", callback=config_run, dest="run_type", help="Only run the alignment routine.") opt_parser.add_option("--calibrate", action="store_true", dest="calibrate", default=False, help="Run the calibration interface.") opt_parser.add_option("--plot", action="store_true", dest="plot", default=False, help="Run the calibration interface.") # Plot options opt_parser.add_option("--dataFile", type="string", action="store", dest="data_file", default='', help="Plot option. Input data file to plot") opt_parser.add_option( "--plotType", type="string", action="store", dest="plot_type", default='', help= f"Plot option. Type of plot to generate. Must be one of the following" f" {parser.ALLOWED_PLOT_TYPES}.") opt_parser.add_option( "--freq", type="string", action="store", dest="plot_freq", default='', help="Plot option. Frequency to plot at. Must be in Hz, MHz, or GHz") opt_parser.add_option( "--phi", type="float", action="store", dest="plot_phi", default=200.0, help="Plot option. Test phi angle to plot at. Must be in degrees " "and between -180 and 180 degrees.") opt_parser.add_option( "--theta", type="float", action="store", dest="plot_theta", default=200.0, help="Plot option. Test theta angle to plot at. Must be in degrees " "and between -180 and 180 degrees.") opt_parser.add_option( "--probePhi", type="float", action="store", dest="plot_p_phi", default=200.0, help="Plot option. Probe phi angle to plot at. Must be in degrees " "and between -180 and 180 degrees.") opt_parser.add_option("--sParams", type="string", action="store", dest="sParams", default="S21", help="Plot option. S parameters to plot.") opt_parser.add_option("--logName", type="string", action="store", dest="log_name", default=None, help="Filename for terminal output log.") opt_parser.add_option("--logPath", type="string", action="store", dest="log_path", default=None, help="Filepath for terminal output log.") opt_parser.add_option( "--dataPath", type="string", action="store", dest="data_path", default=None, help="Filepath for data file taken during experiment.") opt_parser.add_option( "--dataName", type="string", action="store", dest="data_name", default=None, help="Filename for data file taken during experiment.") opt_parser.add_option( "--plotName", type="string", action="store", dest="plot_name", default=None, help="Filename for plot generated during experiment.") opt_parser.add_option( "--plotPath", type="string", action="store", dest="plot_path", default=None, help="Filepath for plot generated during experiment.") opt_parser.add_option( "--setTestPhi", type="float", action="store", dest="test_phi", default=None, help= "Sets the test-side phi angle to the specified angle. Must be in degrees " "and between -180 and 180 degrees.") opt_parser.add_option( "--zeroTestPhi", action="store_true", dest="zero_test_phi", default=False, help="Sets the current test-side phi angle to be the zero reference.") opt_parser.add_option( "--alignTestPhi", action="store_true", dest="align_test_phi", default=False, help="Aligns the test-side phi motor with the end-switch.") # Test Theta Options opt_parser.add_option( "--setTestTheta", type="float", action="store", dest="test_theta", default=None, help= "Sets the test-side theta angle to the specified angle. Must be in degrees " "and between -180 and 180 degrees.") opt_parser.add_option( "--zeroTestTheta", action="store_true", dest="zero_test_theta", default=False, help="Sets the current test-side theta angle to be the zero reference." ) opt_parser.add_option( "--alignTestTheta", action="store_true", dest="align_test_theta", default=False, help="Aligns the test-side test motor with the end-switch.") # Probe Theta Options opt_parser.add_option( "--setProbePhi", type="float", action="store", dest="probe_phi", default=None, help= "Sets the probe-side phi angle to the specified angle. Must be in degrees " "and between -180 and 180 degrees.") opt_parser.add_option( "--zeroProbePhi", action="store_true", dest="zero_probe_phi", default=False, help="Sets the current probe-side phi angle to be the zero reference.") opt_parser.add_option( "--alignProbePhi", action="store_true", dest="align_probe_phi", default=False, help="Aligns the probe-side phi motor with the end-switch.") # Options determining how the motor will rotate opt_parser.add_option("--direction", action="store", dest="direction", default=None, help="The direction in which motor should rotate.") opt_parser.add_option( "--gradualAcceleration", action="store_true", dest="grad_accel", default=None, help= "Gradually accelerate the motor to its maximum frequency. Recommended for test-theta motor." ) opt_parser.add_option( "--jumpAcceleration", action="store_false", dest="grad_accel", help= "Instantly accelerate the motor to its maximum frequency. Recommended for test-phi and probe-phi motors." ) opt_parser.add_option( "--incremental", action="store_true", dest="incremental", default=False, help= "Whether input angle should be interpreted as absolute or relative to current angle." ) # Check to make sure a config file was entered with the -c index = -1 for i in range(len(sys.argv)): if sys.argv[i] == "-c" or sys.argv[i] == "--config": index = i + 1 if index >= len(sys.argv) or index > 0 and opt_parser.has_option( sys.argv[index]): sys.argv.insert(index, None) # Parse command line (options, args) = opt_parser.parse_args() # print(options) # Check for single mode if options.test_phi != None or options.zero_test_phi or options.align_test_phi or \ options.test_theta != None or options.zero_test_theta or options.align_test_theta \ or options.probe_phi != None or options.zero_probe_phi or options.align_probe_phi: if options.run_type == 'f': options.run_type = 's' else: options.run_type = 'e' # Error Checking if options.run_type == "e": util.printf( curr_phase, "Error", "Cannot simultaneously run the alignment routine only and run the system with out " "the alignment routine. See usage for more information on command line options." ) opt_parser.print_help() return False # Config file checks if options.cfg is None: util.printf( curr_phase, "Error", f"Configuration file flag detected but no configuration was detected. See usage " f"for more information on command line options. ") opt_parser.print_help() return False num_modes = int(options.cfg != '') + int(options.run_type == 'a') + int(options.run_type == 's') + \ int(options.calibrate) + int(options.plot) if num_modes == 0: util.printf( curr_phase, "Error", "Cannot configure system as no command lines arguments were inputted." " See usage for more information on command line options. ") opt_parser.print_help() return False if num_modes > 1: util.printf( curr_phase, "Error", "Mutually-exclusive options specified. Cannot simultaneously run the " "calibration routine and the run the full run the system. See usage for more " "information on command line options.") opt_parser.print_help() return False if options.calibrate: options.run_type = "c" if options.plot: options.run_type = "p" if options.data_file == '': util.printf( curr_phase, "Error", f"Plotting requested but no input data file was entered." f" See usage for more information on command line options.") opt_parser.print_help() return False if options.data_file == '' or not options.data_file.endswith(".csv"): util.printf( curr_phase, "Error", f"The input data file entered '{options.data_file}' is not a csv file. " f" See usage for more information on command line options.") opt_parser.print_help() return False if options.plot_type == '': util.printf( curr_phase, "Error", f"Plotting requested but no plot type was specified. " f" See usage for more information on command line options.") opt_parser.print_help() return False if options.plot_type not in parser.ALLOWED_PLOT_TYPES: util.printf( curr_phase, "Error", f"Plotting requested but invalid plot type {options.plot_type} was specified. " f"Plot type must one of the following {parser.ALLOWED_PLOT_TYPES}" f" See usage for more information on command line options.") opt_parser.print_help() return False if options.plot_type == "cutPhi" and options.plot_phi == 200: util.printf( curr_phase, "Error", f"Phi cut plot requested but no phi angle was specified. " f" See usage for more information on command line options.") opt_parser.print_help() return False elif options.plot_type == "cutTheta" and options.plot_theta == 200: util.printf( curr_phase, "Error", f"Theta cut plot requested but no theta angle was specified. " f" See usage for more information on command line options.") opt_parser.print_help() return False if 'MHz' in options.plot_freq: options.plot_freq = 1e6 * float(options.plot_freq[:-3]) elif 'GHz' in options.plot_freq: options.plot_freq = 1e9 * float(options.plot_freq[:-3]) elif 'Hz' in options.plot_freq: options.plot_freq = float(options.plot_freq[:-3]) else: util.printf( curr_phase, "Error", f"Plotting requested but invalid plot frequency {options.plot_freq} was specified. " f"Plot type must be in units of Hz, MHz, or GHz (e.g. 10GHz or \"10 GHz\")." f" See usage for more information on command line options.") opt_parser.print_help() return False if options.cfg != '' and not options.cfg.endswith(".json"): util.printf( curr_phase, "Error", f"The configuration file entered '{options.cfg}' is not a JSON file. " f" See the User Manual for more information on configuration files and " f"usage for more information on command line options.") opt_parser.print_help() return False return options
def process_cmd_line_alt(): """ Alternate version of process_cmd_line. Processes the command line arguments and sets up the system control variables accordingly. If an error occurred, an error message indicating the fault will be printed before the returning False. :return Returns options if no errors occurred, otherwise False. """ # Set up parser opt_parser = OptionParser() opt_parser.prog = "direcMeasure" usage = set_usage(opt_parser.prog) opt_parser.set_usage(usage) opt_parser.set_defaults(run_type="s", verbose=False) # Test Phi Options opt_parser.add_option("--alignOnly", action="callback", callback=config_run, dest="run_type", help="Only run the alignment routine.") opt_parser.add_option( "--setTestPhi", type="float", action="store", dest="test_phi", default=None, help= "Sets the test-side phi angle to the specified angle. Must be in degrees " "and between -180 and 180 degrees.") opt_parser.add_option( "--zeroTestPhi", action="store_true", dest="zero_test_phi", default=False, help="Sets the current test-side phi angle to be the zero reference.") opt_parser.add_option( "--alignTestPhi", action="store_true", dest="align_test_phi", default=False, help="Aligns the test-side phi motor with the end-switch.") # Test Theta Options opt_parser.add_option( "--setTestTheta", type="float", action="store", dest="test_theta", default=None, help= "Sets the test-side theta angle to the specified angle. Must be in degrees " "and between -180 and 180 degrees.") opt_parser.add_option( "--zeroTestTheta", action="store_true", dest="zero_test_theta", default=False, help="Sets the current test-side theta angle to be the zero reference." ) opt_parser.add_option( "--alignTestTheta", action="store_true", dest="align_test_theta", default=False, help="Aligns the test-side test motor with the end-switch.") # Probe Theta Options opt_parser.add_option( "--setProbePhi", type="float", action="store", dest="probe_phi", default=None, help= "Sets the probe-side phi angle to the specified angle. Must be in degrees " "and between -180 and 180 degrees.") opt_parser.add_option( "--zeroProbePhi", action="store_true", dest="zero_probe_phi", default=False, help="Sets the current probe-side phi angle to be the zero reference.") opt_parser.add_option( "--alignProbePhi", action="store_true", dest="align_probe_phi", default=False, help="Aligns the probe-side phi motor with the end-switch.") (options, args) = opt_parser.parse_args() # print(type(options)) print(options) return False
parser.add_option( '-p', '--play', action='store_true', dest='play', help='Play back a track file' ) parser.add_option( '-d', '--device', dest='device', help='MIDI output device number' ) parser.add_option( '-l', '--list-devices', action='store_true', dest='devices', help='list MIDI output devices' ) parser.add_option( '-b', '--backend', dest='backend', default='auto', help='Player backend (pygame or portmidi)' ) parser.prog = 'gambolputty' parser.usage = '%prog [options] filename' options, args = parser.parse_args() filename = args[0] if args else '' def error(message): if options.play or options.devices: print(message) else: from Tkinter import Tk root = Tk() root.withdraw() import tkMessageBox tkMessageBox.showinfo("Gambolputty", message) sys.exit(1)
def setup_parser(): """Setup the option parser.""" parser = OptionParser() parser.description = "%prog (pyafg is an affine fractal generator) is a utility"+\ " to draw affine transformation fractals"+\ " with or without a display. It uses PIL for image rendering, and pygame"+\ " if you want to watch the fractal being drawn." parser.usage = "%prog [options] <fractal.frct>" parser.prog = "pyafg" parser.add_option("-s", "--scale", type = "int", default = 0,\ help = "The scaling factor for your fractal. 100 is usually a good try") parser.add_option("-a", "--autocalc", action = "store_true", default = False,\ help = "Print out autocalced dimensions and offsets for this scaling.") parser.add_option("--speak-int", type = "int", default = 10000,\ help = "The cycles to wait before printing out progress") parser.add_option("-x", "--x-offset", type = "int", default = 0,\ help = "x offset for the fractal. negative values allowed") parser.add_option("-y", "--y-offset", type = "int", default = 0,\ help = "the y offset for the fractal. negative values allowed") parser.add_option("-G", "--geometry", type = "string", default = "",\ help = "Size of the viewing window (or image). In WxH format. eg. 120x240") parser.add_option("-i", "--iterations", type = "int", default = 100000,\ help = "The number of iterations to go through.") parser.add_option("--color-type", type = "int", default = COLOR_NORMAL,\ help = "The type of coloring you want. Choices from COLOR_NORMAL (0),"+\ "COLOR_REGION (1), COLOR_FANCY (2), or COLOR_GRADIENT (3)."+\ "Check the man page for details.") parser.add_option("-g", "--gradient-int", type = "string", default = "1,1,1",\ help = "The interval that RGB go up (or down) by.") parser.add_option("-S", "--gradient-start", type = "string", default = "0,0,0",\ help = "The RGB values that the gradient starts at.") parser.add_option("-E", "--gradient-end", type = "string", default = "255,255,255",\ help = "The RGB values that the gradient ends at.") parser.add_option("--color", type = "string", default = "000255000",\ help = "A RRRGGGBBB string for the color to be used. If color-type is"+\ " 2, you'll need to give as many colors as there are rules in your fractal") parser.add_option("--color-file", type = "string", default = "",\ help = "A file with RRRGGGBBB strings separated by newline. # is a comment character") parser.add_option("-b", "--background", type = "string", default = "000000000",\ help = "Background color of the image.") #parser.add_option("--add-alpha", action = "store_true", default = False,\ # help = "Interpret colors as RRRGGGBBBAAA. This may not work with pygame") parser.add_option("-o", "--save", type = "string", default = "",\ help = "The file to save an image to. If this is set, the pygame display"+\ " will not be shown, and the image generated will be saved to named file") parser.add_option("-q", "--quiet", action = "store_false",\ default = "verbosity", help = "No output") parser.add_option("--progress", action = "store_true", default = False) parser.add_option("-v", "--verbosity", action = "store", type = "int",\ default = 1) return parser
def main(): '''Parse command-line arguments and start up the simulation''' parser = OptionParser() parser.prog = "fs.py" parser.add_option("-f", "--logfile", dest="logfile", default="", help="Send log to file (default: log to stderr)") parser.add_option( "-d", "--debug", dest="debug", default=0, action="count", help= "Turn on debugging output (may be given multiple times to increase debug output)" ) parser.add_option("-t", "--simtime", dest="simtime", default=300, type=int, help="Set amount of simulation time (default: 300 sec)") parser.add_option( "-i", "--interval", dest="interval", default=1.0, type=float, help="Set the simulation tick interval (sec) (default: 1 sec)") parser.add_option("-c", "--configonly", dest="configonly", default=False, action="store_true", help="Just do configuration then exit") parser.add_option( "-s", "--seed", dest="seed", default=None, type="int", help= "Set random number generation seed (default: seed based on system time)" ) (options, args) = parser.parse_args() if len(args) != 1: print >> sys.stderr, "Usage: %s [options] <scenario.[dot,json]>" % ( sys.argv[0]) sys.exit(0) random.seed(options.seed) fscommon.setup_logger(options.logfile, options.debug) sim = FsCore(options.interval, endtime=options.simtime, debug=options.debug) signal.signal(signal.SIGINT, sim.sighandler) sys.path.append(".") sim.run(args[0], configonly=options.configonly)
pfwe = parseFloatWithEsd # cmp func for AtomGroup: def agcmp(ag1, ag2): return ag1.en - ag2.en # global flag for verbose message printing: verbose = True # build option-parser: op = OptionParser(version='0.1.2') op.prog = 'ciftep' ##op.version = '0.1.2' op.description = 'CIFTEP: Generate ORTEP3 Instructions From CIF Files' op.usage = '%prog [options] cif-files' # op.add_option('-o', '--output', type='string', dest='tfname', metavar='OUTPUT', help='Specify output file name') # op.add_option('-c', '--contents', type='choice', choices=['aunit', 'grow', 'cell'],
def main(): parser = OptionParser() parser.prog = "flowmax.py" parser.add_option("-x", "--debug", dest="debug", default=False, action="store_true", help="Turn on debugging output") parser.add_option("-t", "--simtime", dest="simtime", default=300, type=int, help="Set amount of simulation time; default=300 sec") parser.add_option( "-i", "--interval", dest="interval", default=1.0, type=float, help="Set the simulation tick interval (sec); default=1 sec") parser.add_option( "-s", "--snmpinterval", dest="snmpinterval", default=0.0, type=float, help= "Set the interval for dumping SNMP-like counters at each router (specify non-zero value to dump counters); default=no dump" ) parser.add_option( "-S", "--snmpexportfile", dest="snmpexportfile", default=None, help= "Specify file for dumping SNMP-like counters (or 'stdout'); no default" ) parser.add_option("-e", "--exporter", dest="exporter", default="text", help="Set the export type (text,cflow); default=text") parser.add_option( "-z", "--usepsyco", action="store_true", default=False, help="Use psyco for performance improvement; default=no psyco") (options, args) = parser.parse_args() if len(args) != 1: print >> sys.stderr, "Usage: %s [options] <scenario.dot>" % ( sys.argv[0]) sys.exit(0) scenario = args[0] exporter = None if options.exporter == 'text': exporter = text_export_factory elif options.exporter == 'cflow': exporter = cflowd_export_factory elif options.exporter == 'null': exporter = null_export_factory else: print >> sys.stderr, "Invalid export type. Need 'text' or 'cflow'" sys.exit(0) sim = Simulator(options.interval, scenario, exporter, endtime=options.simtime, debug=options.debug, snmpexportinterval=options.snmpinterval, snmpexportfile=options.snmpexportfile) signal.signal(signal.SIGINT, sim.sighandler) if options.usepsyco: try: import psyco print >> sys.stderr, 'Starting psyco' # psyco.log() # psyco.profile(0.01) psyco.full() print >> sys.stderr, 'Done starting psyco' except ImportError: print >> sys.stderr, 'Sorry, no psyco' sim.run()
def main(argv): parser = OptionParser(version = __VERSION__) parser.prog = 'Model Runner' parser.description = 'This program runs a batch job on a directory containing output files from Big Horn.' + \ 'The input data files can describe a historical data set or future model prediction data set.' + \ 'The program outputs a set of averages of temperature and sums of precipitation respectively for ' + \ 'the historical or furture data sets. The output files contain these attributes from different of ' + \ 'of their respective models. The output files are marked in the following format:\n' + \ 'Temp_STATION_MODEL_MODELTYPE_Etc.txt - for temperatures\n' + \ 'Precip_STATION_MODEL_MODELTYPE_Etc.txt - for precipitation\n' parser.add_option("-i", "--input_directory", action='append', dest="input_directory", help="directory to search for input files", type=str) parser.add_option("-o", "--output_directory", action='append', dest="output_directory", help="directory search for output files", type=str) parser.add_option("-d", "--delimiter", dest="delimiter", help="the delimiter to break out the parameters (default='.')", type=str, default='.') parser.add_option("-g", "--nogui", action="store_true", help="the flag that determines whether a gui should not be used") parser.add_option("-f", "--individual_files", action="store_true", dest='individual_files', help="flag that determines whether individual models files should be created (true) or not (false)") parser.add_option("-b", "--beginning_year", action='append', dest="beginning_year", help="the beginning year of the output", type=int) parser.add_option("-e", "--ending_year", action='append', dest="ending_year", help="the ending year of the output", type=int) # TODO: Implement a logger for debugging purposes parser.add_option("-l", "--log", action="store_true", dest='log', help="flag that determines whether to create and write to a debug log file", default=True) options, args = parser.parse_args(argv) start_time = None if options.log: start_time = datetime.datetime.today() log_filename_prefix = '{0:02}_{1:02}_{2:02}_{3:02}_{4:02}_{5:02}_'.format(start_time.hour, start_time.minute, start_time.second, start_time.month, start_time.day, start_time.year) log_filename = log_filename_prefix + 'model_runner_debug.log' # Add log filename to options so it can be retrieved later log_handler = logging.FileHandler(log_filename, mode='w') logging.getLogger().addHandler(log_handler) logging.getLogger().setLevel(20) # Setting the logging level to output information messages (level = 20) logging.info('Program started: ' + str(start_time)) if options.nogui: # Input directory is the only required parameter. if options.input_directory == None: print(parser.prog + ' ' + parser.version) parser.print_help() return else: input_args = create_job_list(options, start_time) run_jobs(input_args) else: # Create the main window app = QApplication([]) # Create the widgets for organizing the file processing # NOTE: I'm testing the capability of using an image icon on a GUI button add_icon_filename = 'plus.gif' add_icon_directory = os.getcwd() + '/resources/images/' if os.path.isdir(add_icon_directory): add_icon_filename = add_icon_directory + add_icon_filename if not os.path.isfile(add_icon_filename): add_icon_filename = None job_list = ModelRunnerGUIQt.JobList(window_title=parser.prog + ' ' + parser.version, add_icon_filename=add_icon_filename, run_job=run_job, create_plots=create_plots, log_filename=log_filename) job_list.show() job_list.raise_() # Run the window main loop app.exec_() if options.log: end_time = datetime.datetime.today() logging.info('Program ended: ' + str(end_time)) if start_time != None: logging.info('Total time: ' + str(get_time_diff_secs(start_time, end_time)) + ' seconds.') logging.shutdown()