def get_opt_parser(): # use module docstring for help output p = OptionParser( usage="%s [OPTIONS] <DIRECTORY CONTAINING DICOMSs> <mount point>" % os.path.basename(sys.argv[0]), version="%prog " + nib.__version__) p.add_options([ Option("-v", "--verbose", action="count", dest="verbose", default=0, help="make noise. Could be specified multiple times"), ]) p.add_options([ Option("-L", "--follow-links", action="store_true", dest="followlinks", default=False, help="Follow symbolic links in DICOM directory"), ]) return p
def main(): global opts (progdir, progname) = os.path.split(sys.argv[0]) usage = "usage: %prog [options] [stl file]" parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_options(options) (opts, args) = parser.parse_args() filename = None if len(args): filename = args[0] a = stltool.stl(filename) (points, faces) = a.unique_vertices(a.facets) if opts.boundary: (pxmin, pymin, pxmax, pymax) = map(float, opts.boundary.split(',')) x = np.array(map(lambda p: p[0], points)) y = np.array(map(lambda p: p[1], points)) z = np.array(map(lambda p: p[2], points)) fig = pp.figure() if opts.boundary: pp.axis([pxmin, pxmax, pymin, pymax]) pp.tricontourf(x, y, z, 256) pp.colorbar() pp.triplot(x, y, faces, 'wo-') pp.title('Correction mesh contour') pp.show()
def get_parser(): parser = OptionParser() parser.add_options(cone_common.COMMON_OPTIONS) parser.add_option("-c", "--configuration", dest="configs", action="append", help="Defines the name of the configuration for the action, can be "\ "specified multiple times to include multiple configurations.", metavar="CONFIG", default=[]) parser.add_option("--config-wildcard", action="append", dest="config_wildcards", help="Wildcard pattern for including configurations, e.g. "\ "product_langpack_*_root.confml", metavar="WILDCARD", default=[]) parser.add_option("--config-regex", action="append", dest="config_regexes", help="Regular expression for including configurations, e.g. "\ "product_langpack_\\d{2}_root.confml", metavar="REGEX", default=[]) parser.add_option("-p", "--project",\ dest="project",\ help="defines the location of current project. Default is the current working directory.",\ default=".",\ metavar="STORAGE") return parser
def get_opt_parser(): # use module docstring for help output p = OptionParser( usage="%s [OPTIONS] [FILE ...]\n\n" % sys.argv[0] + __doc__, version="%prog " + nib.__version__) p.add_options([ Option("-v", "--verbose", action="count", dest="verbose", default=0, help="Make more noise. Could be specified multiple times"), Option("-H", "--header-fields", dest="header_fields", default='', help="Header fields (comma separated) to be printed as well (if present)"), Option("-s", "--stats", action="store_true", dest='stats', default=False, help="Output basic data statistics"), Option("-c", "--counts", action="store_true", dest='counts', default=False, help="Output counts - number of entries for each numeric value " "(useful for int ROI maps)"), Option("--all-counts", action="store_true", dest='all_counts', default=False, help="Output all counts, even if number of unique values > %d" % MAX_UNIQUE), Option("-z", "--zeros", action="store_true", dest='stats_zeros', default=False, help="Include zeros into output basic data statistics (--stats, --counts)"), ]) return p
def main(): parser = OptionParser(usage="%s PATH_TO_ANALYZE\n\n" % sys.argv[0] + __doc__, version="%prog " + __version__) parser.add_options([ Option("-L", "--lib-path", action="store", type='string', help="Output subdirectory path to copy library dependencies"), Option("-d", "--dylibs-only", action="store_true", help="Only analyze files with known dynamic library " "extensions") ]) (opts, paths) = parser.parse_args() if len(paths) < 1: parser.print_help() sys.exit(1) if opts.lib_path is None: opts.lib_path = '.dylibs' lib_filt_func = 'dylibs-only' if opts.dylibs_only else None multi = len(paths) > 1 for path in paths: if multi: print(path) # evaluate paths relative to the path we are working on lib_path = os.path.join(path, opts.lib_path) delocate_path(path, lib_path, lib_filt_func)
def main(): options = [ Option('-d', '--dontcares', dest='dc', default='', help='comma-separated don\'t-cares', metavar='D'), Option('-o', '--ones', dest='ones', default='', help='comma-separated ones', metavar='O'), Option('-z', '--zeros', dest='zeros', default='', help='comma-separated zeros', metavar='Z') ] f = IndentedHelpFormatter() def raw_format(s): return s + '\n' f.format_description = raw_format optparser = OptionParser(description=__doc__, formatter=f) optparser.add_options(options) opts, args = optparser.parse_args() if len(sys.argv) == 1 or args: optparser.print_help() exit() opts.dc = [int(i) for i in opts.dc.split(',') if i] opts.ones = [int(i) for i in opts.ones.split(',') if i] opts.zeros = [int(i) for i in opts.zeros.split(',') if i] soln = qm(dc=opts.dc, ones=opts.ones, zeros=opts.zeros) if len(soln) == 0: sys.stdout.write('contradiction\n') elif len(soln) == 1 and soln[0].count('X') == len(soln[0]): sys.stdout.write('tautology\n') else: sys.stdout.write(' '.join(soln) + '\n')
def _parse_args(self): parser = OptionParser() parser.add_options(self.option_list) self.options, _ = parser.parse_args() if self.options.download_perm_group: try: self.download_perm_groups = [] for group in self.options.download_perm_group.split(','): self.download_perm_groups.append( Group.objects.get(name=group) ) except Group.DoesNotExist: raise SystemExit('The download permissions group doesn\'t exist') else: self.download_perm_groups = [] try: self.owner_group = Group.objects.get(name=self.options.owner_group) except Group.DoesNotExist: raise SystemExit('The owner group specified doesn\'t exist') try: self.upload_user = User.objects.get(username=self.options.upload_user) except User.DoesNotExist: raise SystemExit('The upload user specified doesn\'t exist')
def main(): global opts (progdir, progname) = os.path.split(sys.argv[0]) usage = "usage: %prog [options] file.stl" parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_options(options) (opts, args) = parser.parse_args() points = readpoints() if opts.inifile: import linuxcnc inifile = linuxcnc.ini(opts.inifile) lu = inifile.find("TRAJ", "LINEAR_UNITS") if lu.lower() in ("mm", "metric"): units = 1.0 else: units = 25.4 xmin = float(inifile.find("AXIS_0", "MIN_LIMIT")) * units ymin = float(inifile.find("AXIS_1", "MIN_LIMIT")) * units xmax = float(inifile.find("AXIS_0", "MAX_LIMIT")) * units ymax = float(inifile.find("AXIS_1", "MAX_LIMIT")) * units zbound = 0 if opts.zbound: zbound = opts.zbound points.append(Point(xmin, ymin, zbound)) points.append(Point(xmax, ymax, zbound)) points.append(Point(xmin, ymax, zbound)) points.append(Point(xmax, ymin, zbound)) triangles = voronoi.computeDelaunayTriangulation(points) stldump(sys.stdout, points, triangles)
def _parse_args(self): parser = OptionParser() parser.add_options(self.option_list) self.options, _ = parser.parse_args() if self.options.download_perm_group: try: self.download_perm_groups = [] for group in self.options.download_perm_group.split(','): self.download_perm_groups.append( Group.objects.get(name=group)) except Group.DoesNotExist: raise SystemExit( 'The download permissions group doesn\'t exist') else: self.download_perm_groups = [] try: self.owner_group = Group.objects.get(name=self.options.owner_group) except Group.DoesNotExist: raise SystemExit('The owner group specified doesn\'t exist') try: self.upload_user = User.objects.get( username=self.options.upload_user) except User.DoesNotExist: raise SystemExit('The upload user specified doesn\'t exist')
def main(): """ creates a HAL component. parsees a glade XML file with gtk.builder or libglade calls gladevcp.makepins with the specified XML file to create pins and register callbacks. main window must be called "window1" """ global gladevcp_debug (progdir, progname) = os.path.split(sys.argv[0]) usage = "usage: %prog [options] myfile.ui" parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_options(options) (opts, args) = parser.parse_args() if not args: parser.print_help() sys.exit(1) BASE = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), "..")) libdir = os.path.join(BASE, "lib", "python") sys.path.append(libdir) arhmidir = os.path.join(BASE, "lib", "python", "arhmi") sys.path.append(arhmidir) gladevcp_debug = debug = opts.debug xmlname = args[0] #if there was no component name specified use the xml file name if opts.component is None: opts.component = os.path.splitext(os.path.basename(xmlname))[0] builder = gtk.Builder() # try loading as a gtk.builder project try: builder.add_from_file(xmlname) except: # #try loading as a libglade project # try: # dbg("**** GLADE VCP INFO: Not a GtkBuilder project, trying to load as a GTK builder project") # builder = gtk.glade.XML(xmlname) # builder = GladeBuilder(builder) try: # for arhmi applications LOCALEDIR = os.path.join(BASE, "share", "locale") o = "plasma" gettext.install(o, localedir=LOCALEDIR, unicode=True) gtk.glade.bindtextdomain(o, LOCALEDIR) gtk.glade.textdomain(o) base = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), "..")) sharedir = os.path.join(base, "share", "linuxcnc") gladefile = os.path.join(sharedir, xmlname) builder.add_from_file(gladefile) except Exception,e: print >> sys.stderr, "**** GLADE VCP ERROR: With xml file: %s : %s" % (xmlname, e) sys.exit(0)
def main(): """ The main function. @author: Marco Wegner """ usage = "usage: %prog [options] template1 [template2, ...]" parser = OptionParser(usage, conflict_handler="resolve") parser.add_options(support.get_global_options()) parser.add_options(_get_local_options()) (options, args) = parser.parse_args() # the script has been called without any options or arguments if len(sys.argv) == 1: parser.print_help() sys.exit() delimiters = support.extract_delimiters(options) # check if the template file is defined if len(args) == 0: support.print_error_message("no template file(s) specified") sys.exit() if options.verbose: print "\nExtracting translatable strings from the template files:" super_store = UT3Store() count = 0 for tmpl_file in args: tmpl = UT3Template(tmpl_file, delimiters) tmpl_store = tmpl.parse() num_rem = len(tmpl_store.get_all()) count = count + num_rem super_store.extend(tmpl_store) if options.verbose: tname = os.path.basename(tmpl_file) print " * " + tname + ": " + str(num_rem) + " messages" if options.verbose: num_rem = len(super_store.get_all()) print "\nHandling duplicates: removing %i strings" % (count - num_rem) print "\nRemaining to be written: %i strings" % (num_rem) print "\nWriting the template...\n" pofile = Ut3PoFile(options.outfile) pofile.write(super_store, True) if options.verbose: print "\nDone." return
def initFromCmdLine(): """ Initialize application according to commandline flags.""" app = {} data_dir = resource_filename(__name__, '') # parse command line parser = OptionParser() option_list = [ make_option( '-D', '--debug', action='store_true', dest='debug', help='enable Bottle debug mode [false]', ), make_option( '-n', '--nofork', action='store_true', dest='nofork', help='do not daemonize at start [false]', ), make_option( '-d', '--db-dir', dest='db_dir', help='directory for dbs [/tmp]', ), make_option( '-a', '--data-dir', dest='data_dir', help='prefix for data directories [%s]' % data_dir, ), make_option( '-H', '--host', dest='host', help='hostname to bind on [localhost]', ), make_option( '-p', '--port', type='int', dest='port', help='port to bind to [8080]', ), ] parser.add_options(option_list) parser.set_defaults( debug=False, nofork=False, host='localhost', port=8080, ) options = parser.parse_args()[0] app.update(vars(options)) return app
def __init__(self): usage = "usage: %prog [options]" parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_options(options) self.set_theme_font() (opts, args) = parser.parse_args() self.window = gtk.Window() self.window.set_default_size(1024, 600) xid = None if opts.parent: xid = int(opts.parent) plug = gtk.Plug(xid) for c in self.window.get_children(): self.window.remove(c) plug.add(c) self.window = plug self.window.connect('destroy', self.quit) self.table = gtk.Table(10,5) self.btn_hal= gtk.Button(label="HAL Configuration") self.btn_hal.set_border_width(4) self.btn_hal.connect("clicked", self.halshow_action) self.btn_halscope= gtk.Button(label="HAL Scope") self.btn_halscope.set_border_width(4) self.btn_halscope.connect("clicked", self.halscope_action) self.btn_ladder = gtk.Button(label="Ladder Logic") self.btn_ladder.set_border_width(4) self.btn_ladder.connect("clicked", self.ladder_action) self.btn_teamviewer = gtk.Button(label="Teamviewer") self.btn_teamviewer.set_border_width(4) self.btn_teamviewer.connect("clicked", self.teamviewer_action) self.btn_nautilus = gtk.Button(label="File Manager") self.btn_nautilus.set_border_width(4) self.btn_nautilus.connect("clicked", self.nautilus_action) self.btn_linuxcncop = gtk.Button(label="Linuxcnc Status") self.btn_linuxcncop.set_border_width(4) self.btn_linuxcncop.connect("clicked", self.linuxcnc_status) self.table.attach(self.btn_hal, 0, 1, 0, 1) self.table.attach(self.btn_ladder, 0, 1, 1, 2) self.table.attach(self.btn_linuxcncop, 0, 1, 2, 3) self.table.attach(self.btn_halscope, 1, 2, 0, 1) self.table.attach(self.btn_teamviewer, 1, 2, 1, 2) self.table.attach(self.btn_nautilus, 1, 2, 2, 3) self.window.add(self.table)
def __init__(self): usage = "usage: %prog [options]" parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_options(options) self.set_theme_font() (opts, args) = parser.parse_args() self.window = gtk.Window() self.window.set_default_size(1024, 600) xid = None if opts.parent: xid = int(opts.parent) plug = gtk.Plug(xid) for c in self.window.get_children(): self.window.remove(c) plug.add(c) self.window = plug self.window.connect('destroy', self.quit) self.table = gtk.Table(10, 5) self.btn_hal = gtk.Button(label="HAL Configuration") self.btn_hal.set_border_width(4) self.btn_hal.connect("clicked", self.halshow_action) self.btn_halscope = gtk.Button(label="HAL Scope") self.btn_halscope.set_border_width(4) self.btn_halscope.connect("clicked", self.halscope_action) self.btn_ladder = gtk.Button(label="Ladder Logic") self.btn_ladder.set_border_width(4) self.btn_ladder.connect("clicked", self.ladder_action) self.btn_teamviewer = gtk.Button(label="Teamviewer") self.btn_teamviewer.set_border_width(4) self.btn_teamviewer.connect("clicked", self.teamviewer_action) self.btn_nautilus = gtk.Button(label="File Manager") self.btn_nautilus.set_border_width(4) self.btn_nautilus.connect("clicked", self.nautilus_action) self.btn_linuxcncop = gtk.Button(label="Linuxcnc Status") self.btn_linuxcncop.set_border_width(4) self.btn_linuxcncop.connect("clicked", self.linuxcnc_status) self.table.attach(self.btn_hal, 0, 1, 0, 1) self.table.attach(self.btn_ladder, 0, 1, 1, 2) self.table.attach(self.btn_linuxcncop, 0, 1, 2, 3) self.table.attach(self.btn_halscope, 1, 2, 0, 1) self.table.attach(self.btn_teamviewer, 1, 2, 1, 2) self.table.attach(self.btn_nautilus, 1, 2, 2, 3) self.window.add(self.table)
def main(): parser = OptionParser( usage="%s PATH_TO_ANALYZE\n\n" % sys.argv[0] + __doc__, version="%prog " + __version__, ) parser.add_options([ Option( "-L", "--lib-path", action="store", type="string", help="Output subdirectory path to copy library dependencies", ), Option( "-d", "--dylibs-only", action="store_true", help="Only analyze files with known dynamic library extensions", ), Option( "--executable-path", action="store", type="string", default=os.path.dirname(sys.executable), help=("The path used to resolve @executable_path in dependencies"), ), Option( "--ignore-missing-dependencies", action="store_true", help=("Skip dependencies which couldn't be found and delocate " "as much as possible"), ), ]) (opts, paths) = parser.parse_args() if len(paths) < 1: parser.print_help() sys.exit(1) if opts.lib_path is None: opts.lib_path = ".dylibs" lib_filt_func = "dylibs-only" if opts.dylibs_only else None multi = len(paths) > 1 for path in paths: if multi: print(path) # evaluate paths relative to the path we are working on lib_path = os.path.join(path, opts.lib_path) delocate_path( path, lib_path, lib_filt_func, executable_path=opts.executable_path, ignore_missing=opts.ignore_missing_dependencies, )
def main(): parser = OptionParser( usage="%s WHEEL_OR_PATH_TO_ANALYZE\n\n" % sys.argv[0] + __doc__, version="%prog " + __version__, ) parser.add_options([ Option( "-a", "--all", action="store_true", help="Show all dependencies, including system libs", ), Option( "-d", "--depending", action="store_true", help="Show libraries depending on dependencies", ), ]) (opts, paths) = parser.parse_args() if len(paths) < 1: parser.print_help() sys.exit(1) multi = len(paths) > 1 for path in paths: if multi: print(path + ":") indent = " " else: indent = "" if isdir(path): lib_dict = tree_libs_from_directory(path, ignore_missing=True) lib_dict = stripped_lib_dict(lib_dict, realpath(getcwd()) + psep) else: lib_dict = wheel_libs(path, ignore_missing=True) keys = sorted(lib_dict) if not opts.all: keys = [key for key in keys if filter_system_libs(key)] if not opts.depending: if len(keys): print(indent + ("\n" + indent).join(keys)) continue i2 = indent + " " for key in keys: print(indent + key + ":") libs = lib_dict[key] if len(libs): print(i2 + ("\n" + i2).join(libs))
def main(): """ creates a HAL component. parsees a glade XML file with gtk.builder or libglade calls gladevcp.makepins with the specified XML file to create pins and register callbacks. main window must be called "window1" """ global gladevcp_debug (progdir, progname) = os.path.split(sys.argv[0]) usage = "usage: %prog [options] myfile.ui" parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_options(options) (opts, args) = parser.parse_args() if not args: parser.print_help() sys.exit(1) gladevcp_debug = debug = opts.debug xmlname = args[0] if opts.instance > -1 and not remote_ok: print >> sys.stderr, "gladevcp: cant operate remotely - modules missing" sys.exit(1) #if there was no component name specified use the xml file name if opts.component is None: opts.component = os.path.splitext(os.path.basename(xmlname))[0] #try loading as a libglade project try: builder = gtk.Builder() builder.add_from_file(xmlname) except: try: # try loading as a gtk.builder project dbg("**** GLADE VCP INFO: Not a builder project, trying to load as a lib glade project" ) builder = gtk.glade.XML(xmlname) builder = GladeBuilder(builder) except Exception, e: print >> sys.stderr, "**** GLADE VCP ERROR: With xml file: %s : %s" % ( xmlname, e) sys.exit(0)
def mainparser(harvest=None,with_stdopts=True,**kwargs): """setup option parser""" from optparse import OptionParser kwargs.setdefault('usage','usage: %prog [options] [file(s)]') kwargs.setdefault('version','%prog ' + __version__) parser = OptionParser(**kwargs) parser.set_conflict_handler('resolve') if with_stdopts: parser.add_options(stdopts) if harvest is not None: for optlist in harvest_options(harvest): parser.add_options(optlist) return parser
def main(): """ creates a HAL component. parsees a glade XML file with gtk.builder or libglade calls gladevcp.makepins with the specified XML file to create pins and register callbacks. main window must be called "window1" """ global gladevcp_debug (progdir, progname) = os.path.split(sys.argv[0]) usage = "usage: %prog [options] myfile.ui" parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_options(options) (opts, args) = parser.parse_args() if not args: parser.print_help() sys.exit(1) gladevcp_debug = debug = opts.debug xmlname = args[0] if opts.instance > -1 and not remote_ok: print >> sys.stderr, "gladevcp: cant operate remotely - modules missing" sys.exit(1) #if there was no component name specified use the xml file name if opts.component is None: opts.component = os.path.splitext(os.path.basename(xmlname))[0] #try loading as a libglade project try: builder = gtk.Builder() builder.add_from_file(xmlname) except: try: # try loading as a gtk.builder project dbg("**** GLADE VCP INFO: Not a builder project, trying to load as a lib glade project") builder = gtk.glade.XML(xmlname) builder = GladeBuilder(builder) except Exception,e: print >> sys.stderr, "**** GLADE VCP ERROR: With xml file: %s : %s" % (xmlname,e) sys.exit(0)
def get_opt_parser(): # use module docstring for help output p = OptionParser(usage="%s [OPTIONS] [FILE ...]\n\n" % sys.argv[0] + __doc__, version="%prog " + nib.__version__) p.add_options([ Option("-v", "--verbose", action="count", dest="verbose", default=0, help="Make more noise. Could be specified multiple times"), Option("-H", "--header-fields", dest="header_fields", default='all', help="Header fields (comma separated) to be printed as well" " (if present)"), Option("--ma", "--data-max-abs-diff", dest="data_max_abs_diff", type=float, default=0.0, help="Maximal absolute difference in data between files" " to tolerate."), Option("--mr", "--data-max-rel-diff", dest="data_max_rel_diff", type=float, default=0.0, help="Maximal relative difference in data between files to" " tolerate. If --data-max-abs-diff is also specified," " only the data points with absolute difference greater" " than that value would be considered for relative" " difference check."), Option("--dt", "--datatype", dest="dtype", default=np.float64, help="Enter a numpy datatype such as 'float32'.") ]) return p
def get_opt_parser(): # use module docstring for help output p = OptionParser( usage="%s [OPTIONS] <DIRECTORY CONTAINING DICOMSs> <mount point>" % os.path.basename(sys.argv[0]), version="%prog " + nib.__version__) p.add_options([ Option("-v", "--verbose", action="count", dest="verbose", default=0, help="make noise. Could be specified multiple times"), ]) p.add_options([ Option("-L", "--follow-links", action="store_true", dest="followlinks", default=False, help="Follow symbolic links in DICOM directory"), ]) return p
def main(): usage = "usage: %prog [options] expression" parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_options(options) (opts, args) = parser.parse_args() if not args: parser.print_help() print("examples:") print(" lut5 'i0 & i1 & i2 & i3 & i4'") print(" lut5 'i0 | i1 | i2 | i3 | i4'") print(" lut5 -n2 'i0 ^ i1'") print("# a two-line mux:") print(" lut5 -n3 '(i2 and i1) or (not i2 and i0)'") sys.exit(1) expression = args[0] print("# expression = %s" % (expression)) print("#in: i4 i3 i2 i1 i0 out weight") function = 0 for i in range(1 << int(opts.inputs)): weight = 1 << i i0 = True if i & 1 else False i1 = True if i & 2 else False i2 = True if i & 4 else False i3 = True if i & 8 else False i4 = True if i & 16 else False result = eval(expression) print( "#%2d: %d %d %d %d %d %d" % (i, int(i4), int(i3), int(i2), int(i1), int(i0), int(result)), ) if result: function += weight print(" 0x%x" % (weight)) else: print print("# setp lut5.N.function 0x%x" % (function))
def main(): usage = "usage: %prog [options] expression" parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_options(options) (opts, args) = parser.parse_args() if not args: parser.print_help() print "examples:" print " lut5 'i0 & i1 & i2 & i3 & i4'" print " lut5 'i0 | i1 | i2 | i3 | i4'" print " lut5 -n2 'i0 ^ i1'" print "# a two-line mux:" print " lut5 -n3 '(i2 and i1) or (not i2 and i0)'" print " lut5 -n3 '(i2 & i1) | (~i2 & i0)'" sys.exit(1) expression = args[0] print "# expression = %s" % (expression) print "#in: i4 i3 i2 i1 i0 out weight" function = 0 for i in range(1 << int(opts.inputs)): weight = 1 << i i0 = True if i & 1 else False i1 = True if i & 2 else False i2 = True if i & 4 else False i3 = True if i & 8 else False i4 = True if i & 16 else False result = eval(expression) print "#%2d: %d %d %d %d %d %d" % (i,int(i4),int(i3),int(i2),int(i1),int(i0),int(result)), if result: function += weight print " 0x%x" % (weight) else: print print "# setp lut5.N.function 0x%x" % (function)
def get_opt_parser(): # use module docstring for help output p = OptionParser( usage="%s [OPTIONS] [FILE ...]\n\n" % sys.argv[0] + __doc__, version="%prog " + nib.__version__) p.add_options([ Option("-v", "--verbose", action="count", dest="verbose", default=0, help="Make more noise. Could be specified multiple times"), Option("-H", "--header-fields", dest="header_fields", default='all', help="Header fields (comma separated) to be printed as well" " (if present)"), Option("--ma", "--data-max-abs-diff", dest="data_max_abs_diff", type=float, default=0.0, help="Maximal absolute difference in data between files" " to tolerate."), Option("--mr", "--data-max-rel-diff", dest="data_max_rel_diff", type=float, default=0.0, help="Maximal relative difference in data between files to" " tolerate. If --data-max-abs-diff is also specified," " only the data points with absolute difference greater" " than that value would be considered for relative" " difference check."), Option("--dt", "--datatype", dest="dtype", default=np.float64, help="Enter a numpy datatype such as 'float32'.") ]) return p
def get_opt_parser(): # use module docstring for help output p = OptionParser(usage="%s [OPTIONS] [FILE ...]\n\n" % sys.argv[0] + __doc__, version="%prog " + nib.__version__) p.add_options([ Option("-v", "--verbose", action="count", dest="verbose", default=0, help="Make more noise. Could be specified multiple times"), Option( "-H", "--header-fields", dest="header_fields", default='all', help= "Header fields (comma separated) to be printed as well (if present)" ), ]) return p
def _parse_args(self): parser = OptionParser() parser.add_options(self.option_list) self.options, _ = parser.parse_args()
from django_nose import NoseTestSuiteRunner def run_tests(*test_args, **kwargs): if 'south' in settings.INSTALLED_APPS: from south.management.commands import patch_for_test_db_setup patch_for_test_db_setup() if not test_args: test_args = ['entity_emailer'] kwargs.setdefault('interactive', False) test_runner = NoseTestSuiteRunner(**kwargs) failures = test_runner.run_tests(test_args) sys.exit(failures) if __name__ == '__main__': parser = OptionParser() parser.add_option('--verbosity', dest='verbosity', action='store', default=1, type=int) parser.add_options(NoseTestSuiteRunner.options) (options, args) = parser.parse_args() run_tests(*args, **options.__dict__)
'is_active': False, 'label': 'Default Inactive', 'description': 'Controls the funkiness.', }, }, ) from django_nose import NoseTestSuiteRunner def runtests(*test_args, **kwargs): if 'south' in settings.INSTALLED_APPS: from south.management.commands import patch_for_test_db_setup patch_for_test_db_setup() if not test_args: test_args = ['tests'] test_runner = NoseTestSuiteRunner(**kwargs) failures = test_runner.run_tests(test_args) sys.exit(failures) if __name__ == '__main__': parser = OptionParser() parser.add_option('--verbosity', dest='verbosity', action='store', default=1, type=int) parser.add_options(NoseTestSuiteRunner.options) (options, args) = parser.parse_args() runtests(*args, **options.__dict__)
if 'south' in settings.INSTALLED_APPS: from south.management.commands import patch_for_test_db_setup patch_for_test_db_setup() if not test_args: test_args = ['celery_rpc'] if sys.version_info >= (3, 10, 0): from django.test.runner import DiscoverRunner test_runner = DiscoverRunner(**kwargs) else: test_runner = NoseTestSuiteRunner(**kwargs) failures = test_runner.run_tests(test_args) sys.exit(failures) if __name__ == '__main__': parser = OptionParser() parser.add_option('--verbosity', dest='verbosity', action='store', default=1, type=int) opts = getattr(NoseTestSuiteRunner, 'options', None) if opts: parser.add_options(opts) (options, args) = parser.parse_args() runtests(*args, **options.__dict__)
if __name__ == '__main__': usage = ''' Fit a series of measurements in a file ''' #options .... parser = OptionParser(usage=usage) parser.add_option("-a", '--amc-path', dest="amc-path", default='SPole_winter.amc', help=" -a option: AM input template") parser.add_options('-p', destination='pressure', type=float, default=680.0, help='Ground level pressure (mbar), Default=680mB') parser.add_options('-t', destination='temperature', type=float, default=243.0, help='Ground level temperature (K), Default=243K = -30C') parser.add_options('-e', type=float, default=55.0, help='Elevation of observation, Default=55') parser.add_option("-f", '--filename',
def main(): """ creates a HAL component. parsees a glade XML file with gtk.builder or libglade calls gladevcp.makepins with the specified XML file to create pins and register callbacks. main window must be called "window1" """ global gladevcp_debug (progdir, progname) = os.path.split(sys.argv[0]) usage = "usage: %prog [options] myfile.ui" parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_options(options) (opts, args) = parser.parse_args() if not args: parser.print_help() sys.exit(1) gladevcp_debug = debug = opts.debug xmlname = args[0] #if there was no component name specified use the xml file name if opts.component is None: opts.component = os.path.splitext(os.path.basename(xmlname))[0] #try loading as a libglade project try: builder = gtk.glade.XML(xmlname) builder = GladeBuilder(builder) except: try: # try loading as a gtk.builder project print "**** GLADE VCP INFO: Not a libglade project, trying to load as a GTK builder project" builder = gtk.Builder() builder.add_from_file(xmlname) except: print "**** GLADE VCP ERROR: With xml file: %s" % xmlname sys.exit(0) window = builder.get_object("window1") window.set_title(opts.component) try: halcomp = hal.component(opts.component) except: print "*** GLADE VCP ERROR: Asking for a HAL component using a name that already exists." sys.exit(0) panel = gladevcp.makepins.GladePanel(halcomp, xmlname, builder, None) # at this point, any glade HL widgets and their pins are set up. handlers = load_handlers(opts.usermod, halcomp, builder, opts.useropts) builder.connect_signals(handlers) if opts.parent: # block X errors since gdk error handling silently exits the # program without even the atexit handler given a chance gtk.gdk.error_trap_push() window = xembed.reparent(window, opts.parent) forward = os.environ.get('AXIS_FORWARD_EVENTS_TO', None) if forward: xembed.keyboard_forward(window, forward) window.connect("destroy", on_window_destroy) window.show() # for window resize and or position options if "+" in opts.geometry: try: j = opts.geometry.partition("+") pos = j[2].partition("+") window.move(int(pos[0]), int(pos[2])) except: print "**** GLADE VCP ERROR: With window position data" parser.print_usage() sys.exit(1) if "x" in opts.geometry: try: if "+" in opts.geometry: j = opts.geometry.partition("+") t = j[0].partition("x") else: t = window_geometry.partition("x") window.resize(int(t[0]), int(t[2])) except: print "**** GLADE VCP ERROR: With window resize data" parser.print_usage() sys.exit(1) if opts.gtk_workaround: # work around https://bugs.launchpad.net/ubuntu/+source/pygtk/+bug/507739 # this makes widget and widget_class matches in gtkrc and theme files actually work dbg("activating GTK bug workaround for gtkrc files") for o in builder.get_objects(): if isinstance(o, gtk.Widget): # retrieving the name works only for GtkBuilder files, not for # libglade files, so be cautious about it name = gtk.Buildable.get_name(o) if name: o.set_name(name) if opts.gtk_rc: dbg("**** GLADE VCP INFO: %s reading gtkrc file '%s'" % (opts.component, opts.gtk_rc)) gtk.rc_add_default_file(opts.gtk_rc) gtk.rc_parse(opts.gtk_rc) if opts.theme: dbg("**** GLADE VCP INFO: Switching %s to '%s' theme" % (opts.component, opts.theme)) settings = gtk.settings_get_default() settings.set_string_property("gtk-theme-name", opts.theme, "") # This needs to be done after geometry moves so on dual screens the window maxumizes to the actual used screen size. if opts.maximum: window.window.maximize() if opts.halfile: cmd = ["halcmd", "-f", opts.halfile] res = subprocess.call(cmd, stdout=sys.stdout, stderr=sys.stderr) if res: print >> sys.stderr, "'%s' exited with %d" % (' '.join(cmd), res) sys.exit(res) # User components are set up so report that we are ready halcomp.ready() if handlers.has_key(signal_func): dbg("Register callback '%s' for SIGINT and SIGTERM" % (signal_func)) signal.signal(signal.SIGTERM, handlers[signal_func]) signal.signal(signal.SIGINT, handlers[signal_func]) try: gtk.main() except KeyboardInterrupt: sys.exit(0) finally: halcomp.exit() if opts.parent: gtk.gdk.flush() error = gtk.gdk.error_trap_pop() if error: print "**** GLADE VCP ERROR: X Protocol Error: %s" % str(error)
) try: from django.test.runner import DiscoverRunner as Runner except ImportError: from django.test.simple import DjangoTestSuiteRunner as Runner def runtests(*test_args, **kwargs): if 'south' in settings.INSTALLED_APPS: from south.management.commands import patch_for_test_db_setup patch_for_test_db_setup() if not test_args: test_args = ['uuidfield'] kwargs.setdefault('interactive', False) test_runner = Runner(**kwargs) failures = test_runner.run_tests(test_args) sys.exit(failures) if __name__ == '__main__': parser = OptionParser() parser.add_option('--verbosity', dest='verbosity', action='store', default=1, type=int) parser.add_options(Runner.options) (options, args) = parser.parse_args() runtests(*args, **options.__dict__)
def make_parser(): description = """ Fbuild is a new kind of build system that is designed around caching instead of tree evaluation. """ epilog = '\nTargets:\n{}\n'.format(fbuild.target.help_string()) parser = OptionParser( version=fbuild.__version__, usage='%prog [options] target1 [target2 target3 ...]', description=description, epilog=epilog) parser.add_options([ make_option('-v', '--verbose', action='count', default=0, help='print out extra debugging info'), make_option('--show', action='count', default=1, help='print out extra debugging info'), make_option('-j', '--jobs', dest='threadcount', metavar='N', type='int', default=1, help='Allow N jobs at once'), make_option('--nocolor', action='store_true', default=False, help='Do not use colors'), make_option('--show-threads', action='store_true', default=False, help='Show which thread is running which command'), make_option('--configure', dest='force_configuration', action='store_true', default=False, help='force reconfiguration'), make_option('--buildroot', action='store', default='build', help='where to store the build files (default build)'), make_option('--state-file', action='store', default='fbuild-state.db', help='the name of the state file ' \ '(default buildroot/fbuild-state.db)'), make_option('--log-file', action='store', default='fbuild.log', help='the name of the log file (default fbuild.log)'), make_option('--dump-state', action='store_true', default=False, help='print the state database'), make_option('--clean', dest='clean_buildroot', action='store_true', default=False, help='clean the build directory'), make_option('--delete-function', action='store', help='delete cached data for the specified function'), make_option('--delete-file', action='store', help='delete cached data for the specified file'), make_option('--do-not-save-database', action='store_true', default=False, help='do not save the results of the database for testing.'), make_option('--explain-database', action='store_true', default=False, help='explain why a function was not cached.'), make_option('--database-engine', action='store', choices=('pickle', 'sqlite', 'cache'), default='pickle', help='which database engine to use: (pickle, sqlite). pickle is ' \ 'the default'), ]) return parser
class Builder(object): """docstring for Builder""" __usage__ = "%prog <namespace>.<blueprint> [options]" def __init__(self): super(Builder, self).__init__() self.build_parser() self.config = BuilderConfig(CONFIG_DIR) self.plugins = self.config.plugins self.loaded_plugins = [] self.aliases = copy(self.config.aliases) self.blueprints = self.get_blueprints() self.logger = logger self.plugin_data = {} # end def __init__ @property def help(self): return self.parser.print_help() # end def def build_parser(self): self.parser = OptionParser(prog='builder', usage=self.__usage__) self.parser.add_option('--logging-level', help='Set logging level. (Default: INFO)', action="store", default='INFO') self.parser.add_option('--list-namespaces', help='List the available plugins.', action="store_true", default=False) self.parser.add_option('--list-blueprints', help='List the available blueprints for a plugin.', action="store_true", default=False) # end def build_parser def parse_blueprint_name(self, fullname): parts = fullname.split('.', 1) namespace = parts[0] blueprint_name = "default" if len(parts) == 1 else parts[1] return namespace, blueprint_name # end def parse_plugin_blueprint def main(self, input_args=sys.argv): cmd_args = copy(input_args) script = cmd_args.pop(0) if not cmd_args: print self.help sys.exit(2) elif '--list-namespaces' in cmd_args: print "Installed plugins:" print ", ".join(sorted(self.blueprints.keys())) sys.exit(0) # end if blueprint_fullname = cmd_args.pop(0) if blueprint_fullname.startswith('-'): options, args = self.parser.parse_args(input_args) # if parsed and -h/--help is not there print help anyways # since the args are incorrect. print "Blueprint must the be the first argument." print self.help sys.exit(2) # end if # end if aliased = self.aliases.get(blueprint_fullname) if aliased: alias_args = aliased.split() blueprint_fullname = alias_args.pop(0) # Only one level of recursion for aliases at this time. nested_alias = self.aliases.get(blueprint_fullname) if nested_alias: blueprint_fullname = nested_alias # end if # insert that alias's args before the command line args new_cmd_args = alias_args new_cmd_args.extend(cmd_args) cmd_args = new_cmd_args # end if namespace, blueprint_name = self.parse_blueprint_name(blueprint_fullname) if namespace not in self.blueprints: print "Error finding blueprint '%s'.\n" % blueprint_fullname print "Installed plugins:" print ", ".join(sorted(self.plugins)) print "Namespaces from plugins:" print ", ".join(sorted(self.blueprints.keys())) sys.exit(1) # end if if '--list-blueprints' in cmd_args: print "Installed blueprints for '%s':" % (namespace) print ", ".join(self.blueprints[namespace].keys()) sys.exit(0) # end if blueprint_cls = self.blueprints[namespace].get(blueprint_name) if not blueprint_cls: print "No blueprint '%s'" % (blueprint_name) print "Blueprints for '%s':" % (namespace) print "\t", ", ".join(self.blueprints[namespace].keys()) sys.exit(1) # end if self.parser.add_options(blueprint_cls.options) self.parser.prog = '%s %s' % (self.parser.prog, blueprint_fullname) options, args = self.parser.parse_args(cmd_args) # set logging level self.logger.setLevel(getattr(logging, options.logging_level.upper())) exit_code = 0 if not self.run_blueprint( blueprint_cls, self.build_context(options, self.config.get_blueprint_config(blueprint_fullname)), args): exit_code = 1 # end if sys.exit(exit_code) # end def main def build_context(self, option_values, blueprint_config): context = {} context.update(blueprint_config) for option, value in option_values.__dict__.iteritems(): if value != None: context[option] = value # end if # end for if 'list_blueprints' in context: del context['list_blueprints'] # end if if 'list_namespaces'in context: del context['list_namespaces'] # end if if 'logging_level'in context: del context['logging_level'] # end if return context # end def build_context def run_blueprint(self, blueprint_cls, context, args): blueprint = blueprint_cls() valid = blueprint.validate(context, args) success = False if valid: try: blueprint.run(context, args) success = True except Exception, run_ex: print "Error running '%s' blueprint:\n" % (blueprint) print run_ex try: blueprint.rollback(context, args) except Exception, roll_ex: print "Error rolling back '%s' blueprint:\n" % (blueprint) print roll_ex
def main(): parser = OptionParser(usage="%s WHEEL_FILENAME\n\n" % sys.argv[0] + __doc__, version="%prog " + __version__) parser.add_options([ Option("-L", "--lib-sdir", action="store", type='string', default='.dylibs', help="Subdirectory in packages to store copied libraries"), Option("-w", "--wheel-dir", action="store", type='string', help="Directory to store delocated wheels (default is to " "overwrite input)"), Option("-v", "--verbose", action="store_true", help="Show more verbose report of progress and failure"), Option("-k", "--check-archs", action="store_true", help="Check architectures of depended libraries"), Option("-d", "--dylibs-only", action="store_true", help="Only analyze files with known dynamic library " "extensions"), Option("--require-archs", action="store", type='string', help="Architectures that all wheel libraries should " "have (from 'intel', 'i386', 'x86_64', 'i386,x86_64')"), Option("-i", "--insert_file", action="store", type='string', help="Force insert file") ]) (opts, wheels) = parser.parse_args() if len(wheels) < 1: parser.print_help() sys.exit(1) multi = len(wheels) > 1 if opts.wheel_dir: wheel_dir = expanduser(opts.wheel_dir) if not exists(wheel_dir): os.makedirs(wheel_dir) else: wheel_dir = None if opts.require_archs is None: require_archs = [] if opts.check_archs else None elif ',' in opts.require_archs: require_archs = [s.strip() for s in opts.require_archs.split(',')] else: require_archs = opts.require_archs lib_filt_func = 'dylibs-only' if opts.dylibs_only else None for wheel in wheels: if multi or opts.verbose: print('Fixing: ' + wheel) if wheel_dir: out_wheel = pjoin(wheel_dir, basename(wheel)) else: out_wheel = wheel copied = delocate_wheel(wheel, out_wheel, lib_filt_func=lib_filt_func, lib_sdir=opts.lib_sdir, require_archs=require_archs, check_verbose=opts.verbose, insert_file=opts.insert_file) if opts.verbose and len(copied): print("Copied to package {0} directory:".format(opts.lib_sdir)) copy_lines = [' ' + name for name in sorted(copied)] print('\n'.join(copy_lines))
def main(argv=sys.argv): """ Merge a configuration/layer to the project. """ parser = OptionParser(version="%%prog %s" % VERSION) parser.add_options(cone_common.COMMON_OPTIONS) parser.add_option("-c", "--configuration",\ dest="configuration",\ help="defines the name of the target configuration for the action",\ metavar="CONFIG") parser.add_option("-p", "--project",\ dest="project",\ help="defines the location of current project. Default is the current working directory.",\ default=".",\ metavar="STORAGE") group = OptionGroup(parser, 'Merge options', 'The merge functionality is meant to merge configurations/layers ' 'from a remote project (defined with -r) to the current project (defined with -p). ' 'Default value for the current project is the currently working directory. ' 'A project can be either a folder or a cpf/zip file. There are two ways to ' 'use merge: merge configuration roots (multiple layers), or specific layers. ' 'See the ConE documentation for details and examples.') group.add_option("-r", "--remote",\ dest="remote",\ help="defines the location of remote storage",\ metavar="STORAGE") group.add_option("-s", "--sourceconfiguration",\ dest="sourceconfiguration",\ help="defines the name of the remote configuration inside the remote storage for the merge action. "\ "Default is the active root of the remote project.",\ metavar="CONFIG") group.add_option("--sourcelayer", help="Defines a specific layer to use as the layer to merge "\ "from the remote project. Must be the layer root (ConfML file)."\ "For example: --sourcelayer assets/somelayer/root.confml", metavar="LAYER_ROOT", default=None) group.add_option("--targetlayer", help="Defines a specific layer (root) to use as the layer to merge "\ "into the target project. Must be the layer root (ConfML file)."\ "For example: --targetlayer assets/somelayer/root.confml", metavar="LAYER_ROOT", default=None) group.add_option("--rename",\ action="store_true", dest="rename",\ help="defines that the merged layers need to be renamed", default=False) group.add_option("--all",\ action="store_true", dest="all",\ help="Defines that the entire configuration (all layers) needs to be merged. "\ "This has no effect when merging layers directly using --sourcelayer and --targetlayer.", default=False) group.add_option("-l", "--layer",\ dest="layers",\ type="int", action="append", help="Define the layers of the source configuration that are included to merge action. "\ "The layer operation can be used several times in a single command. "\ "Note that this can only be used when merging configuration roots, not "\ "specific layers using --sourcelayer and --targetlayer. "\ "Example -l -1 --layer=-2, which would append a layers -1 and -2 to the layers => layers = -1,-2", metavar="LAYERS",\ default=None) group.add_option("--merge-policy", help="Specifies the merge policy to use when merging layers. "\ "Possible values: "\ "replace-add - Add/replace files from source layer, but leave other files in the target as they are. "\ " "\ "overwrite-layer - Overwrite the entire layer (remove all previous content).", default=MergePolicy.REPLACE_ADD) parser.add_option_group(group) (options, _) = parser.parse_args(argv) cone_common.handle_common_options(options) # Check the passed options if not MergePolicy.is_valid(options.merge_policy): parser.error("Invalid merge policy: %s\nMust be one of %s" % (options.merge_policy, '\n'.join(MergePolicy.ALL))) if not options.remote: parser.error("Remote project must be given") if options.layers and (options.sourcelayer or options.targetlayer): parser.error("Specifying layer indices using --layer is not supported when using --sourcelayer or --targetlayer!") if options.sourcelayer and not options.targetlayer: parser.error("Merging a layer into a configuration is not supported at the moment!") if options.sourcelayer and not options.sourcelayer.lower().endswith('.confml'): parser.error("Source layer root should be a .confml file") if options.targetlayer and not options.targetlayer.lower().endswith('.confml'): parser.error("Target layer root should be a .confml file") if not options.sourcelayer and options.targetlayer: parser.error("Cannot merge a configuration into a layer!") # If layers for configuration root merging are not specifically given, # the default is the last layer if options.layers is None: options.layers = [-1] target_project = api.Project(api.Storage.open(options.project,"a", username=options.username, password=options.password)) source_project = api.Project(api.Storage.open(options.remote,"r", username=options.username, password=options.password)) print "Target project: %s" % options.project print "Source project: %s" % options.remote target_config = None try: if options.sourcelayer and options.targetlayer: print "Target layer: %s" % options.targetlayer print "Source layer: %s" % options.sourcelayer try: source_config = source_project.get_configuration(options.sourcelayer) except exceptions.NotFound: raise MergeFailedException("Layer root '%s' not found in source project" % options.sourcelayer) try: target_config = target_project.get_configuration(options.targetlayer) except exceptions.NotFound: logger.info('Creating new layer %s' % (options.targetlayer)) target_config = target_project.create_configuration(options.targetlayer) print "Merging layers..." merge_configuration_layer(source_config, target_config, options.merge_policy) else: # Merging a configuration root into a configuration root if options.all: layer_indices = None else: layer_indices = utils.distinct_array(options.layers) def find_layers(source_config, target_config): return find_layers_to_merge( layer_indices = layer_indices, rename = options.rename, sourceconfig = source_config, targetconfig = target_config) merge_config_root_to_config_root( source_project = source_project, target_project = target_project, source_config = options.sourceconfiguration, target_config = options.configuration, layer_finder_func = find_layers, merge_policy = options.merge_policy) except MergeFailedException, e: print "Could not merge: %s" % e sys.exit(2)
def getOptions(): arguments = OptionParser() arguments.add_options(["--username", "--password", "--firstyear"]) return arguments.parse_args()[0]
n_ch = len(Channels_dat) plt.pcolor(np.ma.array(np.abs(Con_cc),mask=np.eye(Con_cc.shape[0])) ,cmap=plt.cm.cool) #plt.colorbar() if ProbeFileName is not None and len(edges(ChannelGraph))>0: ptsx1,ptsy1 = np.array(edges(ChannelGraph)).T plt.plot(ptsx1+.5,ptsy1+.5,'kx',ms=10,mew=3) ax = plt.gca() ax.set_xticks(np.arange(n_ch)+.5) ax.set_yticks(np.arange(n_ch)+.5) ax.set_xticklabels(ChNames,rotation='vertical') ax.set_yticklabels(ChNames) basename = basename_noext(ProbeFileName) if ProbeFileName else basename_noext(DatFileName) outpath = os.path.join(output_dir or ProbeFileName and os.path.dirname(ProbeFileName) or DatDir,"%s_crosstalk.png"%basename) print("saving figure in %s"%outpath) plt.savefig(outpath) if __name__ == '__main__': usage = """%prog your_dat_file.dat [options] %prog -h displays help""" parser = OptionParser(usage) parser.add_options([caton.myopts.probe,caton.myopts.output]) (opts,args) = parser.parse_args() check_crosstalk(args[0],opts.probe,opts.output)
#!/usr/bin/env python import sys,os,shutil from optparse import OptionParser from caton.core import classify_from_raw_data import caton.myopts usage = """ This is the main script that you use to spike-sort your data. Just make the probe file and you're good to go (see documentation). If you don't specify a probe file or probe directory, I will use every probe file in directory of dat file. I will prompt you for sample rate and number of channels if no xml file is found. %prog your_dat_file.dat [options] %prog -h displays help""" parser = OptionParser(usage) parser.add_options([caton.myopts.probe,caton.myopts.max_spikes,caton.myopts.output,caton.myopts.fast,caton.myopts.fast2,caton.myopts.params]) parser.add_option("--probe-dir",action="store",dest="probe_dir",help="Run the clustering script once for every probe file in the specified directory. Defaults to the directory of the data file. If you want to select a single probe file, use the -p (or --probe=) option.") if __name__ == '__main__': (opts,args) = parser.parse_args() if len(args) == 0: parser.error("Must specify a dat file") DatFileName = args[0] if not os.path.exists(DatFileName): parser.error("raw data file not found: %s"%DatFileName) if opts.probe is not None: probe_files = [opts.probe] else:
def getOptions(): arguments = OptionParser() arguments.add_options(["--email", "--password"]) return arguments.parse_args()[0]
def main(): """ creates a HAL component. parsees a glade XML file with Gtk.builder or libglade calls gladevcp.makepins with the specified XML file to create pins and register callbacks. main window must be called "window1" """ global gladevcp_debug (progdir, progname) = os.path.split(sys.argv[0]) usage = "usage: %prog [options] myfile.ui" parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_options(options) (opts, args) = parser.parse_args() if not args: parser.print_help() sys.exit(1) gladevcp_debug = debug = opts.debug xmlname = args[0] #if there was no component name specified use the xml file name if opts.component is None: opts.component = os.path.splitext(os.path.basename(xmlname))[0] #try loading as a libglade project try: builder = Gtk.Builder() builder.add_from_file(xmlname) except: try: # try loading as a Gtk.builder project dbg("**** GLADE VCP INFO: Not a builder project, trying to load as a lib glade project") builder = Gtk.glade.XML(xmlname) builder = GladeBuilder(builder) except Exception as e: print("**** GLADE VCP ERROR: With xml file: %s : %s" % (xmlname,e), file=sys.stderr) sys.exit(0) window = builder.get_object("window1") window.set_title(opts.component) try: halcomp = hal.component(opts.component) except: print("*** GLADE VCP ERROR: Asking for a HAL component using a name that already exists.", file=sys.stderr) sys.exit(0) panel = gladevcp.makepins.GladePanel( halcomp, xmlname, builder, None) # at this point, any glade HL widgets and their pins are set up. handlers, mod, obj = load_handlers(opts.usermod,halcomp,builder,opts.useropts) # so widgets can call handler functions - give them refeence to the handler object panel.set_handler(obj) builder.connect_signals(handlers) # This option puts the gladevcp panel into a plug and pushed the plug's # X window id number to standard output - so it can be reparented exterally # it also forwards events to qtvcp if opts.push_XID: if not opts.debug: # supress warnings when x window closes warnings.filterwarnings("ignore") # block X errors since Gdk error handling silently exits the # program without even the atexit handler given a chance Gdk.error_trap_push() forward = os.environ.get('QTVCP_FORWARD_EVENTS_TO', None) if forward: xembed.keyboard_forward(window, forward) # This option reparents gladevcp in a given X window id. # it also forwards keyboard events from gladevcp to AXIS if opts.parent: if not opts.debug: # supress warnings when x window closes warnings.filterwarnings("ignore") # block X errors since Gdk error handling silently exits the # program without even the atexit handler given a chance Gdk.error_trap_push() window = xembed.reparent(window, opts.parent) forward = os.environ.get('AXIS_FORWARD_EVENTS_TO', None) if forward: xembed.keyboard_forward(window, forward) window.connect("destroy", on_window_destroy) window.show() # for window resize and or position options if "+" in opts.geometry: try: j = opts.geometry.partition("+") pos = j[2].partition("+") window.move( int(pos[0]), int(pos[2]) ) except: print("**** GLADE VCP ERROR: With window position data", file=sys.stderr) parser.print_usage() sys.exit(1) if "x" in opts.geometry: try: if "+" in opts.geometry: j = opts.geometry.partition("+") t = j[0].partition("x") else: t = window_geometry.partition("x") window.resize( int(t[0]), int(t[2]) ) except: print("**** GLADE VCP ERROR: With window resize data", file=sys.stderr) parser.print_usage() sys.exit(1) if opts.gtk_rc: dbg( "**** GLADE VCP INFO: %s reading gtkrc file '%s'" %(opts.component,opts.gtk_rc)) Gtk.rc_add_default_file(opts.gtk_rc) Gtk.rc_parse(opts.gtk_rc) if opts.theme: dbg("**** GLADE VCP INFO: Switching %s to '%s' theme" %(opts.component,opts.theme)) settings = Gtk.Settings.get_default() settings.set_string_property("gtk-theme-name", opts.theme, "") # This needs to be done after geometry moves so on dual screens the window maxumizes to the actual used screen size. if opts.maximum: window.window.maximize() if opts.always_above_flag: window.set_keep_above(True) if opts.halfile: if opts.halfile[-4:] == ".tcl": cmd = ["haltcl", opts.halfile] else: cmd = ["halcmd", "-f", opts.halfile] res = subprocess.call(cmd, stdout=sys.stdout, stderr=sys.stderr) if res: print("'%s' exited with %d" %(' '.join(cmd), res), file=sys.stderr) sys.exit(res) # User components are set up so report that we are ready halcomp.ready() GSTAT.forced_update() # push the XWindow id number to standard out if opts.push_XID or opts.parent: w_id = window.get_property('window').get_xid() print(w_id, file=sys.stdout) sys.stdout.flush() if signal_func in handlers: dbg("Register callback '%s' for SIGINT and SIGTERM" %(signal_func)) signal.signal(signal.SIGTERM, handlers[signal_func]) signal.signal(signal.SIGINT, handlers[signal_func]) try: Gtk.main() except KeyboardInterrupt: sys.exit(0) finally: halcomp.exit() if opts.parent or opts.push_XID: Gdk.flush() error = Gdk.error_trap_pop() if error and opts.debug: print("**** GLADE VCP ERROR: X Protocol Error: %s" % str(error), file=sys.stderr)
def get_opt_parser(): # use module docstring for help output p = OptionParser( usage="%s [OPTIONS] <LOG> <REGEX> [IGNOREREGEX]\n" % sys.argv[0] + __doc__ + """ LOG: string a string representing a log line filename path to a log file (/var/log/auth.log) "systemd-journal" search systemd journal (systemd-python required) REGEX: string a string representing a 'failregex' filename path to a filter file (filter.d/sshd.conf) IGNOREREGEX: string a string representing an 'ignoreregex' filename path to a filter file (filter.d/sshd.conf) Copyright (c) 2004-2008 Cyril Jaquier, 2008- Fail2Ban Contributors Copyright of modifications held by their respective authors. Licensed under the GNU General Public License v2 (GPL). Written by Cyril Jaquier <*****@*****.**>. Many contributions by Yaroslav O. Halchenko and Steven Hiscocks. Report bugs to https://github.com/fail2ban/fail2ban/issues """, version="%prog " + version) p.add_options([ Option("-d", "--datepattern", help="set custom pattern used to match date/times"), Option("-e", "--encoding", help="File encoding. Default: system locale"), Option("-r", "--raw", action='store_true', help="Raw hosts, don't resolve dns"), Option("-L", "--maxlines", type=int, default=0, help="maxlines for multi-line regex"), Option("-m", "--journalmatch", help="journalctl style matches overriding filter file. " "\"systemd-journal\" only"), Option('-l', "--log-level", type="choice", dest="log_level", choices=('heavydebug', 'debug', 'info', 'notice', 'warning', 'error', 'critical'), default=None, help="Log level for the Fail2Ban logger to use"), Option("-v", "--verbose", action='store_true', help="Be verbose in output"), Option("-D", "--debuggex", action='store_true', help="Produce debuggex.com urls for debugging there"), Option("--print-no-missed", action='store_true', help="Do not print any missed lines"), Option("--print-no-ignored", action='store_true', help="Do not print any ignored lines"), Option("--print-all-matched", action='store_true', help="Print all matched lines"), Option("--print-all-missed", action='store_true', help="Print all missed lines, no matter how many"), Option("--print-all-ignored", action='store_true', help="Print all ignored lines, no matter how many"), Option("-t", "--log-traceback", action='store_true', help="Enrich log-messages with compressed tracebacks"), Option("--full-traceback", action='store_true', help="Either to make the tracebacks full, not compressed (as by default)"), ]) return p
def add_options(self, option_list): self.base_options = (self.base_options + option_list) OptionParser.add_options(self, option_list)
def __init__(self): usage = "usage: %prog [options] /dev/video_device_name" parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_options(options) (opts, args) = parser.parse_args() if not args: parser.print_help() sys.exit(1) self.window = Gtk.Window() self.window.set_default_size(1024, 600) xid = None if opts.parent: xid = int(opts.parent) plug = Gtk.Plug.new(xid) for c in self.window.get_children(): self.window.remove(c) plug.add(c) self.window = plug self.drawingarea = Gtk.DrawingArea() self.window.add(self.drawingarea) self.window.connect('destroy', self.quit) # Create GStreamer pipeline self.pipeline = Gst.Pipeline() # Create bus to get events from GStreamer pipeline self.bus = self.pipeline.get_bus() self.bus.add_signal_watch() self.bus.connect('message::error', self.on_error) # This is needed to make the video output in our DrawingArea: self.bus.enable_sync_message_emission() self.bus.connect('sync-message::element', self.on_sync_message) # Create GStreamer elements # testing: self.src = Gst.ElementFactory.make('videotestsrc', None) self.src = Gst.ElementFactory.make('v4l2src', None) self.src.set_property("device", args[0]) # cameracaps = gst.caps_from_string("video/x-raw, format=YV12 width=1280, height=720, framerate=30/1") cameracaps = Gst.Caps.from_string("image/jpeg, width=1280, height=720, framerate=30/1") self.camerafilter = Gst.ElementFactory.make("capsfilter", "filter") self.camerafilter.set_property("caps", cameracaps) self.jpegdec = Gst.ElementFactory.make('jpegdec', 'jpegdec') # self.sink = Gst.ElementFactory.make('autovideosink', None) self.sink = Gst.ElementFactory.make('xvimagesink', None) self.sink.set_property("sync", "false") # Add elements to the pipeline self.pipeline.add(self.src) self.pipeline.add(self.camerafilter) self.pipeline.add(self.jpegdec) self.pipeline.add(self.sink) self.src.link(self.camerafilter) self.camerafilter.link(self.jpegdec) self.jpegdec.link(self.sink)
def _parse_args(self): parser = OptionParser() parser.add_options(self.option_list) self.options, _ = parser.parse_args()
def main(): """ creates a HAL component. parsees a glade XML file with gtk.builder or libglade calls gladevcp.makepins with the specified XML file to create pins and register callbacks. main window must be called "window1" """ global gladevcp_debug (progdir, progname) = os.path.split(sys.argv[0]) usage = "usage: %prog [options] myfile.ui" parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_options(options) (opts, args) = parser.parse_args() if not args: parser.print_help() sys.exit(1) BASE = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), "..")) libdir = os.path.join(BASE, "lib", "python") sys.path.append(libdir) arhmidir = os.path.join(BASE, "lib", "python", "arhmi") sys.path.append(arhmidir) gladevcp_debug = debug = opts.debug xmlname = args[0] #if there was no component name specified use the xml file name if opts.component is None: opts.component = os.path.splitext(os.path.basename(xmlname))[0] builder = gtk.Builder() # try loading as a gtk.builder project try: builder.add_from_file(xmlname) except: # #try loading as a libglade project # try: # dbg("**** GLADE VCP INFO: Not a GtkBuilder project, trying to load as a GTK builder project") # builder = gtk.glade.XML(xmlname) # builder = GladeBuilder(builder) try: # for arhmi applications LOCALEDIR = os.path.join(BASE, "share", "locale") o = "plasma" gettext.install(o, localedir=LOCALEDIR, unicode=True) gtk.glade.bindtextdomain(o, LOCALEDIR) gtk.glade.textdomain(o) base = os.path.abspath( os.path.join(os.path.dirname(sys.argv[0]), "..")) sharedir = os.path.join(base, "share", "linuxcnc") gladefile = os.path.join(sharedir, xmlname) builder.add_from_file(gladefile) except Exception, e: print >> sys.stderr, "**** GLADE VCP ERROR: With xml file: %s : %s" % ( xmlname, e) sys.exit(0)
def main(): """ Create report of existing report data. """ parser = OptionParser(version="%%prog %s" % VERSION) parser.add_options(cone_common.COMMON_OPTIONS) group = OptionGroup(parser, 'Report options', 'The report function generates a report using previously generated '\ 'intermediary report data as input.') group.add_option("-i", "--input-data",\ action="append",\ help="Defines an input file for report generation. "\ "If specified more than once, the data of all specified "\ "report data files is merged.", metavar="FILE", default=[]) group.add_option("-d", "--input-data-dir",\ help="Defines a directory containing the data files to use for "\ "generating the report. This is an alternative to specifying "\ "a number of --input-data files. The order of the data files "\ "is determined by the generation time stamps found in the data "\ "files.", metavar="DIR", default=None) group.add_option("-r", "--report",\ dest="report",\ action="store", type="string", help="Specifies the report file to create."\ "Example -r report.html.", metavar="FILE",\ default="report.html") group.add_option("--report-option",\ action="append", help="Specifies the report verbose options, that defines "\ "what data is included to the report. The option can be "\ "used multiple times."\ "choises=[default|all]"\ "Example --report-option=all", metavar="OPTION",\ default=[]) group.add_option("-t", "--template",\ dest="template",\ action="store", type="string", help="Template used in report generation."\ "Example -t report_template.html.", metavar="FILE",\ default=None) parser.add_option_group(group) (options, args) = parser.parse_args() cone_common.handle_common_options(options) if len(options.input_data) == 0 and not options.input_data_dir: parser.error("Input data must be specified with either --input-data or --input-data-dir") if len(options.input_data) > 0 and options.input_data_dir: parser.error("Both --input-data and --input-data-dir specified, use one or the other.") if options.input_data_dir and not os.path.isdir(options.input_data_dir): parser.error('Given --input-data-dir does not exist or is not a directory.') if options.input_data: files = options.input_data else: files = get_input_data_files(options.input_data_dir) if len(files) == 0: parser.error("At least one input data file must be specified.") # Load all data files data_reports = [] for data_file in files: print "Loading data file '%s'" % data_file data = generation_report.load_report_data(data_file) data_reports.append(data) # Sort by time stamp data_reports.sort(key=lambda entry: entry.generation_timestamp) # Generate the report print "Generating report to '%s'" % options.report generation_report.generate_report(data_reports, options.report, options.template, [ROOT_PATH], options.report_option) print "Done!'"
#-*-coding:UTF-8-*- ''' Created on 2016年6月14日 @author: rkzhang ''' import json, pika from optparse import OptionParser from pika import credentials opt_parser = OptionParser() opt_parser.add_options("-r", "--routing-key", dest="routing_key", help = "Routing key for message " + " (e.g. myalert.im)") opt_parser.add_options("-m", "--message", dest="message", help="Message text for alert.") args = opt_parser.parse_args()[0] creds_broker = pika.PlainCredentials("sample", "sample") conn_params = pika.ConnectionParameters("", virtual_host="/", credentials = creds_broker) conn_broker = pika.BlockingConnection(conn_params) channel = conn_broker.channel() msg = json.dumps(args.message) msg_props = pika.BasicProperties() msg_props.content_type = "application/json" msg_props.durable = False channel.basic_publish(exchange, routing_key, body, properties, mandatory, immediate)
def main(): """ Export configurations. """ parser = OptionParser(version="%%prog %s" % VERSION) parser.add_options(cone_common.COMMON_OPTIONS) parser.add_option("-c", "--configuration", dest="configs", action="append", help="Defines the name of the configuration for the action, can be "\ "specified multiple times to include multiple configurations.", metavar="CONFIG", default=[]) parser.add_option("--config-wildcard", action="append", dest="config_wildcards", help="Wildcard pattern for including configurations, e.g. "\ "product_langpack_*_root.confml", metavar="WILDCARD", default=[]) parser.add_option("--config-regex", action="append", dest="config_regexes", help="Regular expression for including configurations, e.g. "\ "product_langpack_\\d{2}_root.confml", metavar="REGEX", default=[]) parser.add_option("-p", "--project", dest="project", help="defines the location of current project. Default is the "\ "current working directory.",\ default=".", metavar="STORAGE") group = OptionGroup(parser, 'Export options', 'The export action is intended for exporting configurations '\ 'from one project (storage) to another. A project can be a '\ 'folder, a CPF or ZIP file, or a Carbon web storage URL. '\ # An ugly way to make newlines, someone should look into # sub-classing optparse.HelpFormatter... ' '\ 'Two different ways of exporting are supported: '\ ' '\ '1. Exporting multiple configurations into one new project using --remote '\ ' '\ '2. Exporting configurations into a number of new projects using --export-dir') group.add_option("-r", "--remote", dest="remote", help="Defines the location of remote storage. All configurations included using "\ "--configuration, --config-wildcard and --config-regex are exported into "\ "the storage. If the remote storage location is not given, the default "\ "location is determined based on the first included source configuration name. "\ "E.g. 'example.confml' would be exported into 'example.cpf'", metavar="STORAGE") group.add_option("--export-dir", help="Defines the directory where each included configuration is exported "\ "as a new project.", default=None) group.add_option("--export-format", help="Defines the format into which projects are exported when using "\ "--export-dir. Possible values are 'cpf' (the default) and 'dir'.", default=None) group.add_option("-a","--add", dest="added", action="append", type="string", help="Adds a configuration layer to the given configuration as last element. "\ "The add operation can be used several times in a single command and it "\ "can create even an empty layer. "\ "Example --add foo/root.confml --add bar/root-confml.", metavar="CONFIG", default=None) group.add_option("--run-action", dest="action", action="append", type="string", help="Adds a execution of extra step that can manipulate the configuration before it is exported to external storage. "\ "The --run-action operation can be used several times in a single command and it "\ "will execute the actions in given order."\ "Example --run-action=fix, which would execute fix action during export.", metavar="PLUGIN", default=None) group.add_option("--exclude-folders", dest="exclude_empty_folders", action="store_true", help="Excludes empty folders from export", default=False) group.add_option("--exclude-content-filter", dest="exclude_content_filter", help="Filters out files and folders from content folder which matches with "\ "the given regular expression. Matching is case-insensitive. "\ "Example --exclude-content-filter=\".*\.sisx|.*\.sis|.*\.wgz|.*wgt\" "\ "Filters out all files with extension sis, sisx, wgz or wgt.", default=None) group.add_option("--include-content-filter", dest="include_content_filter", help="Filters out files and folders from content folder which don't match with "\ "the given regular expression. Matching is case-insensitive. "\ "Example --include-content-filter=\".*(manual|configurator).*\" "\ "Filters out all content files which don't have manual or configurator in their path.", default=None) parser.add_option_group(group) (options, args) = parser.parse_args() cone_common.handle_common_options(options) # Check options if options.export_format and options.export_dir is None: parser.error( "--export-format can only be used in conjunction with --export-dir" ) if options.export_dir and options.remote: parser.error( "--export-dir and --remote cannot be used at the same time") if options.export_format and options.export_format.lower() not in ('dir', 'cpf'): parser.error("Invalid export format '%s'" % options.export_format) if options.export_dir and not (options.configs or options.config_wildcards or options.config_regexes): parser.error( "Use of --export-dir requires at least one configuration to be specified" ) if options.export_dir and os.path.isfile(options.export_dir): parser.error("Given export directory '%s' is a file") try: run_export(options) except ExportFailedException, e: parser.error(str(e))
def getOptions(): arguments = OptionParser() arguments.add_options(["--username", "--password", "--file"]) arguments.set_default("file", "mint_backup_%s.csv" % str(date.today())) return arguments.parse_args()[0] # options
def getOptions(): arguments = OptionParser() arguments.add_options(["--username", "--password", "--firstyear"]) return arguments.parse_args()[0]
def main(): signal.signal(signal.SIGUSR1, signal.SIG_IGN) if len(sys.argv)>1: pid=PidContext(True) if sys.argv[1]=='--kill': if pid.signal(signal.SIGTERM): print("Send terminate signal") return else: print("Daemon not running") return elif sys.argv[1]=='--stop': if pid.signal(signal.SIGUSR1): print("Send stop current cycle signal") return else: print("Daemon not running") return try: plugin=sys.argv[1] except : print('first argument must be plugin name !', file=sys.stderr) sys.exit(1) plug_module='plugins.'+plugin __import__(plug_module) plugin=sys.modules[plug_module] for name in plugin_points: if not hasattr(plugin, name): print('Invalid plugin - missing attribute %s'% name, file=sys.stderr) sys.exit(4) opt_parser=OptionParser("%s plugin|--kill|--stop options directory_to_store" %sys.argv[0]) opt_parser.add_option('--proxy', help="HTTP proxy to use, otherwise system setting is used") opt_parser.add_option('--no-proxy', dest='no_proxy', action='store_true', help='Do not use proxy, even if set in system') opt_parser.add_option('-r', '--resume', action='store_true', help='Resumes form from last run - starts on last unfinished page '+ 'and restores queue of unfinished downloads') opt_parser.add_option('-s', '--stop-after', dest='stop_after', type='int', help='Stop approximatelly after x minutes (valid only if not daemon)') opt_parser.add_option('-c', '--continue-after', dest='continue_after', type='int', help='Continue approximatelly after x minutes (valid only for daemon)') opt_parser.add_option('-d', '--debug', action='store_true', help='Debug logging') opt_parser.add_option('--daemon', action='store_true', help='Run as daemon') opt_parser.add_option('--user', help='Run under this user') opt_parser.add_option('--group', help='Run under this group') opt_parser.add_option('-l', '--log', help="Log file") if hasattr(plugin, 'OPTIONS'): opt_parser.add_options(plugin.OPTIONS) options,args=opt_parser.parse_args(sys.argv[2:]) if len(args)<1: opt_parser.print_help() sys.exit(2) base_dir=args[0] if not os.path.exists(base_dir): print('The output directory %s does not exists, exiting' % base_dir, file=sys.stderr) sys.exit(3) if options.daemon: def get_id(name, fn): if not name: return try: return fn(name)[2] except KeyError: pass options.stop_after=0 try: pid=PidContext() except PidContext.AlreadyRunningError: print("Downloader is already running", file=sys.stderr) sys.exit(5) uid= get_id(options.user, pwd.getpwnam) gid = get_id(options.group, grp.getgrnam) context_args={'uid':uid, 'gid':gid, 'working_directory':os.getcwd(), 'pidfile':pid, 'files_preserve':[pid]} #context_args.update({'stdout': sys.stdout, 'stderr':sys.stderr}) with DaemonContext(**context_args): init(plugin, base_dir, options) logging.info("Started daemon with encoding %s", sys.getdefaultencoding()) errors=0 while True: was_error=run(plugin, base_dir, options) if not was_error: errors=0 to_sleep=int(options.continue_after or 0)*60 or 3600 logging.info("Finished a run, will wait %d", to_sleep) # run task on finish else: errors+=1 limit=10 if errors>limit: logging.error('Limit of %d fatal errors reach - stopping daemon', limit) break to_sleep=plugin.MAX_WAIT logging.info("Finished with error will retry after %d", to_sleep) time.sleep(to_sleep) else: init(plugin, base_dir, options) run(plugin, base_dir, options)
def __init__(self): sys.excepthook = self.excepthook INIPATH = None usage = "usage: %prog [options] myfile.ui" parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_options(options) # remove [-ini filepath] that linuxcnc adds if being launched as a screen # keep a reference of that path for i in range(len(sys.argv)): if sys.argv[i] =='-ini': # delete -ini del sys.argv[i] # pop out the ini path INIPATH = sys.argv.pop(i) break (opts, args) = parser.parse_args() # initialize QApp so we can pop up dialogs now. self.app = QtWidgets.QApplication(sys.argv) # we import here so that the QApp is initialized before # the Notify library is loaded because it uses DBusQtMainLoop # DBusQtMainLoop must be initialized after to work properly from qtvcp import qt_makepins, qt_makegui # ToDo: pass specific log levels as an argument, or use an INI setting if not opts.debug: # Log level defaults to DEBUG, so set higher if not debug logger.setGlobalLevel(logger.ERROR) # a specific path has been set to load from or... # no path set but -ini is present: default qtvcp screen...or # oops error if args: basepath=args[0] elif INIPATH: basepath = "qt_cnc" else: log.error('Error in path') sys.exit() # set paths using basename PATH = Paths(basepath, bool(INIPATH)) ################# # Screen specific ################# if INIPATH: log.debug('Building A Linuxcnc Main Screen') import linuxcnc # internationalization and localization import locale, gettext # pull info from the INI file self.inifile = linuxcnc.ini(INIPATH) self.inipath = INIPATH # screens require more path info PATH.add_screen_paths() # International translation locale.setlocale(locale.LC_ALL, '') locale.bindtextdomain(PATH.DOMAIN, PATH.LOCALEDIR) gettext.install(PATH.DOMAIN, localedir=PATH.LOCALEDIR, unicode=True) gettext.bindtextdomain(PATH.DOMAIN, PATH.LOCALEDIR) # if no handler file specified, use stock test one if not opts.usermod: log.info('No handler file specified on command line') target = os.path.join(PATH.CONFIGPATH, '%s_handler.py' % PATH.BASENAME) source = os.path.join(PATH.SCREENDIR, 'tester/tester_handler.py') if PATH.HANDLER is None: message = (""" Qtvcp encountered an error; No handler file was found. Would you like to copy a basic handler file into your config folder? This handker file will allow display of your screen and basic keyboard jogging. The new handlerfile's path will be: %s Pressing cancel will close linuxcnc.""" % target) rtn = QtWidgets.QMessageBox.critical(None, "QTVCP Error", message,QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel) if rtn == QtWidgets.QMessageBox.Ok: try: shutil.copy(source, target) except IOError as e: log.critical("Unable to copy handler file. %s" % e) sys.exit(0) except: log.critical("Unexpected error copying handler file:", sys.exc_info()) sys.exit(0) opts.usermod = PATH.HANDLER = target else: log.critical('No handler file found or specified. User requested stopping') else: opts.usermod = PATH.HANDLER # specify the HAL component name if missing if opts.component is None: log.info('No HAL component base name specified on command line using: {}'.format(PATH.BASENAME)) opts.component = PATH.BASENAME ################# # VCP specific ################# else: log.debug('Building A VCP Panel') # if no handler file specified, use stock test one if not opts.usermod: log.info('No handler file specified - using {}'.format(PATH.HANDLER)) opts.usermod = PATH.HANDLER # specify the HAL component name if missing if opts.component is None: log.info('No HAL component base name specified - using: {}'.format(PATH.BASENAME)) opts.component = PATH.BASENAME ############## # Build ui ############## #if there was no component name specified use the xml file name if opts.component is None: opts.component = PATH.BASENAME # initialize HAL try: self.halcomp = hal.component(opts.component) except: log.critical("Asking for a HAL component using a name that already exists?") sys.exit(0) # initialize the window window = qt_makegui.MyWindow(self.halcomp, PATH) # load optional user handler file if opts.usermod: log.debug('Loading the handler file') window.load_extension(opts.usermod) # add filter to catch keyboard events log.debug('Adding the key events filter') myFilter = qt_makegui.MyEventFilter(window) self.app.installEventFilter(myFilter) # actually build the widgets window.instance() # make QT widget HAL pins self.panel = qt_makepins.QTPanel(self.halcomp, PATH, window, opts.debug) # call handler file's initialized function if opts.usermod: if "initialized__" in dir(window.handler_instance): log.debug('''Calling the handler file's initialized__ function''') window.handler_instance.initialized__() # All Widgets should be added now - synch them to linuxcnc STATUS.forced_update() # User components are set up so report that we are ready log.debug('Set HAL ready') self.halcomp.ready() # embed us into an X11 window (such as AXIS) if opts.parent: window = xembed.reparent_qt_to_x11(window, opts.parent) forward = os.environ.get('AXIS_FORWARD_EVENTS_TO', None) log.critical('Forwarding events to AXIS is not well tested yet') if forward: xembed.XEmbedFowarding(window, forward) # push the window id for embedment into an external program if opts.push_XID: wid = int(window.winId()) print >> sys.stdout,wid sys.stdout.flush() # for window resize and or position options if "+" in opts.geometry: log.debug('-g option: moving window') try: j = opts.geometry.partition("+") pos = j[2].partition("+") window.move( int(pos[0]), int(pos[2]) ) except: log.critical("With window position data") parser.print_usage() sys.exit(1) if "x" in opts.geometry: log.debug('-g option: resizing') try: if "+" in opts.geometry: j = opts.geometry.partition("+") t = j[0].partition("x") else: t = window_geometry.partition("x") window.resize( int(t[0]), int(t[2]) ) except: log.critical("With window resize data") parser.print_usage() sys.exit(1) # always on top if opts.always_top: window.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) # theme (styles in QT speak) specify a qss file if opts.theme: window.apply_styles(opts.theme) # appy qss file or default theme else: window.apply_styles() # title if INIPATH: title = 'QTvcp-Screen-%s'% opts.component else: title = 'QTvcp-Panel-%s'% opts.component window.setWindowTitle(title) log.debug('Show window') # maximize if opts.maximum: window.showMaximized() # fullscreen elif opts.fullscreen: window.showFullScreen() else: window.show() if INIPATH: self.postgui() # catch control c and terminate signals signal.signal(signal.SIGTERM, self.shutdown) signal.signal(signal.SIGINT, self.shutdown) # start loop self.app.exec_() # now shut it all down self.shutdown()
def __init__(self): sys.excepthook = self.excepthook INIPATH = None usage = "usage: %prog [options] myfile.ui" parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_options(options) # remove [-ini filepath] that linuxcnc adds if being launched as a screen # keep a reference of that path for i in range(len(sys.argv)): if sys.argv[i] == '-ini': # delete -ini del sys.argv[i] # pop out the ini path INIPATH = sys.argv.pop(i) break (opts, args) = parser.parse_args() if sys.version_info.major > 2: # so web engine can load local images sys.argv.append("--disable-web-security") # initialize QApp so we can pop up dialogs now. self.app = QtWidgets.QApplication(sys.argv) # we import here so that the QApp is initialized before # the Notify library is loaded because it uses DBusQtMainLoop # DBusQtMainLoop must be initialized after to work properly from qtvcp import qt_makepins, qt_makegui # ToDo: pass specific log levels as an argument, or use an INI setting if opts.debug: # Log level defaults to INFO, so set lower if in debug mode logger.setGlobalLevel(logger.DEBUG) if opts.verbose: # Log level defaults to INFO, so set lowest if in verbose mode logger.setGlobalLevel(logger.VERBOSE) # a specific path has been set to load from or... # no path set but -ini is present: default qtvcp screen...or # oops error if args: basepath = args[0] elif INIPATH: basepath = "qt_cnc" else: PATH.set_paths() # set paths using basename PATH.set_paths(basepath, bool(INIPATH)) # keep track of python version during this transition if sys.version_info.major > 2: ver = 'Python 3' else: ver = 'Python 2' ################# # Screen specific ################# if INIPATH: LOG.info( 'green<Building A Linuxcnc Main Screen with {}>'.format(ver)) import linuxcnc # internationalization and localization import locale, gettext # pull info from the INI file self.inifile = linuxcnc.ini(INIPATH) self.inipath = INIPATH # screens require more path info PATH.add_screen_paths() # International translation locale.setlocale(locale.LC_ALL, '') locale.bindtextdomain(PATH.DOMAIN, PATH.LOCALEDIR) gettext.install(PATH.DOMAIN, localedir=PATH.LOCALEDIR) gettext.bindtextdomain(PATH.DOMAIN, PATH.LOCALEDIR) # if no handler file specified, use stock test one if not opts.usermod: LOG.info('No handler file specified on command line') target = os.path.join(PATH.CONFIGPATH, '%s_handler.py' % PATH.BASENAME) source = os.path.join(PATH.SCREENDIR, 'tester/tester_handler.py') if PATH.HANDLER is None: message = (""" Qtvcp encountered an error; No handler file was found. Would you like to copy a basic handler file into your config folder? This handler file will allow display of your screen and basic keyboard jogging. The new handlerfile's path will be: %s Pressing cancel will close linuxcnc.""" % target) rtn = QtWidgets.QMessageBox.critical( None, "QTVCP Error", message, QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel) if rtn == QtWidgets.QMessageBox.Ok: try: shutil.copy(source, target) except IOError as e: LOG.critical("Unable to copy handler file. %s" % e) sys.exit(0) except: LOG.critical( "Unexpected error copying handler file:", sys.exc_info()) sys.exit(0) opts.usermod = PATH.HANDLER = target else: LOG.critical( 'No handler file found or specified. User requested stopping' ) else: opts.usermod = PATH.HANDLER # specify the HAL component name if missing if opts.component is None: LOG.info( 'No HAL component base name specified on command line using: {}' .format(PATH.BASENAME)) opts.component = PATH.BASENAME ################# # VCP specific ################# else: LOG.info('green<Building A VCP Panel with {}>'.format(ver)) # if no handler file specified, use stock test one if not opts.usermod: LOG.info('No handler file specified - using {}'.format( PATH.HANDLER)) opts.usermod = PATH.HANDLER # specify the HAL component name if missing if opts.component is None: LOG.info( 'No HAL component base name specified - using: {}'.format( PATH.BASENAME)) opts.component = PATH.BASENAME ############## # Build ui ############## #if there was no component name specified use the xml file name if opts.component is None: opts.component = PATH.BASENAME # initialize HAL try: self.halcomp = hal.component(opts.component) self.hal = QComponent(self.halcomp) except: LOG.critical( "Asking for a HAL component using a name that already exists?") raise Exception( '"Asking for a HAL component using a name that already exists?' ) # initialize the window window = qt_makegui.VCPWindow(self.hal, PATH) if opts.useropts: window.USEROPTIONS_ = opts.useropts else: window.USEROPTIONS_ = None # load optional user handler file if opts.usermod: LOG.debug('Loading the handler file') window.load_extension(opts.usermod) try: window.web_view = QWebView() except: window.web_view = None # do any class patching now if "class_patch__" in dir(window.handler_instance): window.handler_instance.class_patch__() # add filter to catch keyboard events LOG.debug('Adding the key events filter') myFilter = qt_makegui.MyEventFilter(window) self.app.installEventFilter(myFilter) # actually build the widgets window.instance() # make QT widget HAL pins self.panel = qt_makepins.QTPanel(self.hal, PATH, window, opts.debug) # call handler file's initialized function if opts.usermod: if "initialized__" in dir(window.handler_instance): LOG.debug( '''Calling the handler file's initialized__ function''') window.handler_instance.initialized__() # All Widgets should be added now - synch them to linuxcnc STATUS.forced_update() # call a HAL file after widgets built if opts.halfile: if opts.halfile[-4:] == ".tcl": cmd = ["haltcl", opts.halfile] else: cmd = ["halcmd", "-f", opts.halfile] res = subprocess.call(cmd, stdout=sys.stdout, stderr=sys.stderr) if res: print >> sys.stderr, "'%s' exited with %d" % (' '.join(cmd), res) self.shutdown() # User components are set up so report that we are ready LOG.debug('Set HAL ready') self.halcomp.ready() # embed us into an X11 window (such as AXIS) if opts.parent: window = xembed.reparent_qt_to_x11(window, opts.parent) forward = os.environ.get('AXIS_FORWARD_EVENTS_TO', None) LOG.critical('Forwarding events to AXIS is not well tested yet') if forward: xembed.XEmbedFowarding(window, forward) # push the window id for embedment into an external program if opts.push_XID: wid = int(window.winId()) print >> sys.stdout, wid sys.stdout.flush() # for window resize and or position options if "+" in opts.geometry: LOG.debug('-g option: moving window') try: j = opts.geometry.partition("+") pos = j[2].partition("+") window.move(int(pos[0]), int(pos[2])) except Exception as e: LOG.critical("With -g window position data:\n {}".format(e)) parser.print_help() self.shutdown() if "x" in opts.geometry: LOG.debug('-g option: resizing') try: if "+" in opts.geometry: j = opts.geometry.partition("+") t = j[0].partition("x") else: t = opts.geometry.partition("x") window.resize(int(t[0]), int(t[2])) except Exception as e: LOG.critical("With -g window resize data:\n {}".format(e)) parser.print_help() self.shutdown() # always on top if opts.always_top: window.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) # theme (styles in QT speak) specify a qss file if opts.theme: window.apply_styles(opts.theme) # appy qss file or default theme else: window.apply_styles() # title if INIPATH: title = 'QTvcp-Screen-%s' % opts.component else: title = 'QTvcp-Panel-%s' % opts.component window.setWindowTitle(title) LOG.debug('Show window') # maximize if opts.maximum: window.showMaximized() # fullscreen elif opts.fullscreen: window.showFullScreen() else: self.panel.set_preference_geometry() window.show() if INIPATH: self.postgui() # catch control c and terminate signals signal.signal(signal.SIGTERM, self.shutdown) signal.signal(signal.SIGINT, self.shutdown) if opts.usermod and "before_loop__" in dir(window.handler_instance): LOG.debug('''Calling the handler file's before_loop__ function''') window.handler_instance.before_loop__() LOG.info('Preference path: {}'.format(PATH.PREFS_FILENAME)) # start loop self.app.exec_() # now shut it all down self.shutdown()
from django_nose import NoseTestSuiteRunner if django.VERSION >= (1, 7): # New Apps loading mechanism django.setup() def runtests(*test_args, **kwargs): if 'south' in settings.INSTALLED_APPS: from south.management.commands import patch_for_test_db_setup patch_for_test_db_setup() if not test_args: test_args = ['celery_rpc'] test_runner = NoseTestSuiteRunner(**kwargs) failures = test_runner.run_tests(test_args) sys.exit(failures) if __name__ == '__main__': parser = OptionParser() parser.add_option('--verbosity', dest='verbosity', action='store', default=1, type=int) opts = getattr(NoseTestSuiteRunner, 'options', None) if opts: parser.add_options(opts) (options, args) = parser.parse_args() runtests(*args, **options.__dict__)