def result(socket, img): num = CLI.getDataRSP(socket, STR_DETECTION_NUM, 4) int_num = int.from_bytes(num, byteorder='little', signed=True) if int_num == 0: return data = CLI.getDataRSP(socket, STR_DETECTION_DATA, 4 * 6 * int_num) int_data = [] for i in range(int_num * 6): tmp = data[i * 4:(i * 4) + 4] int_tmp = int.from_bytes(tmp, byteorder='little', signed=True) int_data.append(int_tmp) for i in range(int_num): print("x_min " + str(int_data[(i * 6)]) + ", " + "x_max " + str(int_data[(i * 6) + 1]) + ", " + "y_min " + str(int_data[(i * 6) + 2]) + ", " + "y_max " + str(int_data[(i * 6) + 3]) + ", " + "score " + str(int_data[(i * 6) + 4]) + ", " + "class " + str(int_data[(i * 6) + 5])) x_min = int((int_data[(i * 6)] * img.shape[1]) / 256) x_max = int((int_data[(i * 6) + 1] * img.shape[1]) / 256) y_min = int((int_data[(i * 6) + 2] * img.shape[0]) / 256) y_max = int((int_data[(i * 6) + 3] * img.shape[0]) / 256) score = str(round(int_data[(i * 6) + 4] * 100 / 256, 1)) cv2.rectangle(img, (x_min, y_min), (x_max, y_max), (0, 0, 255), 1) position = (x_min, y_min) class_name = getClassList("voc-model-labels.txt") cv2.putText(img, class_name[int_data[(i * 6) + 5]] + score, position, cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255, 128), 1) CLI.setDataRSP(socket, STR_DETECTION_NUM, 4, b'\x00\x00\x00\x00')
def __init__(self, argv): """Define to operands `a` and `b`.""" super(Operator, self).__init__(argv) self.a = CLI.Required("LHS operator", dtype=float) self.b = CLI.Required("RHS operator", dtype=float)
def test_valid_arguments(self): """The method should correctly perform its operation if its given valid arguments.""" test_args = ['rename', 'new*'] mock_expand_pattern.return_value = self.new_pattern CLI.rename(self.test_set, test_args) mock_assert_msg(mock_change_pattern.assert_called_once_with, [self.new_pattern], "The method fails to perform the change_pattern operation correctly.")
def test_too_few_arguments(self): """The method should recognize and raise an error if it is given too few arguments.""" test_args = ['rename'] with self.assertRaises(CLI.ArgumentAmountError, msg="The method fails to recognize and raise an error if too few arguments are given."): CLI.rename(self.test_set, test_args) mock_assert_msg(mock_change_pattern.assert_not_called, [], "The method tries to perform an operation even though an error was raised.")
def test_invalid_pattern(self): """The method should recognize and raise an error if it is given an invalid pattern.""" test_args = ['rename', 'newInvalid'] mock_expand_pattern.side_effect = CLI.PatternExpansionError("Invalid pattern") with self.assertRaises(CLI.PatternExpansionError, msg="The method fails to recognize and raise an error if given an invalid pattern."): CLI.rename(self.test_set, test_args) mock_assert_msg(mock_change_pattern.assert_not_called, [], "The method tries to perform an operation even though an error was raised.")
def test_too_many_arguments(self): """The method should recognize and raise an error if it is given too many arguments.""" test_args = ['rename', 'new*', 'extra'] mock_expand_pattern.return_value = self.new_pattern with self.assertRaises(CLI.ArgumentAmountError, msg="The method fails to recognize and raise an error if too many arguments are given."): CLI.rename(self.test_set, test_args) mock_assert_msg(mock_change_pattern.assert_not_called, [], "The method tries to perform an operation even though an error was raised.")
def test_no_file_set_selected(self): """The method should recognize and raise an error if no file set was selected / i.e. the file set is passed as None.""" test_args = ['rename', 'new*'] mock_expand_pattern.return_value = self.new_pattern with self.assertRaises(CLI.CLIRuntimeError, msg="The method fails to recognize and raise an error if no file set is selected."): CLI.rename(None, test_args) mock_assert_msg(mock_change_pattern.assert_not_called, [], "The method tries to perform an operation even though an error was raised.")
def test_full_fix(self): """The method should perform a complete fix if the additional keyword 'all' is given.""" test_args = ['fix', 'all'] CLI.fix(self.test_set, test_args) mock_assert_msg( mock_fix.assert_called_once_with, [True], "The method fails to initiate a full fix if the appropriate arguments are given." )
def test_normal_fix(self): """The method should perform a gap-only fix if no further arguments are given.""" test_args = ['fix'] CLI.fix(self.test_set, test_args) mock_assert_msg( mock_fix.assert_called_once_with, [], "The method fails to initiate a basic fix if no further arguments are given." )
def test_no_sets(self): """The method should notify the user if no file sets are available.""" CLI.file_set_cache = [] CLI._enumerate_available_sets() mock_assert_msg( mock_print.assert_called_once_with, ["No file sets have been found in this directory."], "The method fails to notify the user if no file sets are available." )
def test_set_same_pattern_already_exists(self): """The method should recognize and raise an error if a file set with the same pattern is already registered in the file_set_cache.""" test_args = ['rename', 'new*'] mock_expand_pattern.return_value = self.new_pattern new_set = FileSet(('new', ''), []) CLI.file_set_cache = [new_set] with self.assertRaises(CLI.CLIRuntimeError, msg="The metod fails to recognize and raise an error if a file set with the new pattern already exists."): CLI.rename(self.test_set, test_args) mock_assert_msg(mock_change_pattern.assert_not_called, [], "The method tries to perform an operation even though an error was raised.")
def test_list_available_sets(self): """The method should run _enumerate_available_sets if no number is given.""" test_args = ['choose'] CLI.file_set_cache = [self.test_set0, self.test_set1] CLI.choose(None, test_args) mock_assert_msg( mock_enumerate_sets.assert_called_once, [], "The method fails to call _enumerate_file_sets when no set number is given." )
def test_one_set(self): """The method should list the set if only a single one has been found.""" test_set = FileSet(self.pattern, []) CLI.file_set_cache = [test_set] CLI._enumerate_available_sets() mock_assert_msg( mock_print.assert_called_once_with, [0, '\t', str(test_set)], "The method fails to list a single available file set.")
def test_no_file_set_selected(self): """The method should recognize and raise an error if no file set is selected.""" test_args = ['fix'] with self.assertRaises( CLI.CLIRuntimeError, msg= "The method fails to recognize when no file set is selected."): CLI.fix(None, test_args) mock_assert_msg( mock_fix.assert_not_called, [], "The method tries to perform a fix operation even though an error was raised." )
def main(argv): path, basename = os.path.split(argv[0]) cname = NAMETOOBJECT.get(basename, None) if cname is None: print "Did not find key %s, making links." % (basename, ) make_links() else: try: klass = _get_object(cname) except ValueError, err: print err print "Using generic CLI." CLI.run_generic_cli() else:
def main(argv): path, basename = os.path.split(argv[0]) cname = NAMETOOBJECT.get(basename, None) if cname is None: print "Did not find key %s, making links." % (basename,) make_links() else: try: klass = _get_object(cname) except ValueError, err: print err print "Using generic CLI." CLI.run_generic_cli() else:
def test_too_few_arguments(self): """The method should recognize and raise an error if too few arguments are given.""" test_args = ['create'] with self.assertRaises( CLI.ArgumentAmountError, msg= "The method fails to recognize and raise an error when too few arguments are given." ): CLI.create(test_args) mock_assert_msg( mock_files_detected.assert_not_called, [], "The method creates a file set even though an error was raised.")
def test_set_with_too_many_files(self): """The method should raise a CLIRuntimeError if the file set has too many files to perform 'fix all'.""" test_args = ['fix', 'all'] mock_fix.side_effect = FileSet.TooManyFilesError("Too many files.") with self.assertRaises( CLI.CLIRuntimeError, msg= "The method fails to react correctly when the file set contains too many files to fix all." ): CLI.fix(self.test_set, test_args) mock_assert_msg( mock_fix.assert_called_once_with, [True], "The method doesn't actually try to perform the fix operation.")
def test_invalid_second_argument(self): """The method should recognize and raise an error if the second given argument is not 'all'.""" test_args = ['fix', 'arg'] with self.assertRaises( CLI.InputProcessingError, msg= "The method fails to recognize when an invalid second argument is given." ): CLI.fix(self.test_set, test_args) mock_assert_msg( mock_fix.assert_not_called, [], "The method tries to perform a fix operation even though an error was raised." )
def test_too_many_arguments(self): """The method should recognize and raise an error if too many arguments are given.""" test_args = ['fix', 'all', 'now'] with self.assertRaises( CLI.ArgumentAmountError, msg= "The method fails to recognize when too many arguments are given." ): CLI.fix(self.test_set, test_args) mock_assert_msg( mock_fix.assert_not_called, [], "The method tries to perform a fix operation even though an error was raised." )
def _generic_call(self, argv): meth = getattr(self._client, argv[0]) args, kwargs = CLI.breakout_args(argv[1:], vars(self._client)) rv = apply(meth, args, kwargs) if rv: self._print(rv) return rv
def test_logger(self): logger = CLI.CommandLineInterface() logger.unknown_command("1232", "fff") logger.unknown_command("1232", "fff2") self.assertEqual(logger.log_number, 2) logger.unknown_command("2312","31112") self.assertEqual(logger.log_number , 3)
def main(): """Start point of the program""" # Parse arguments from command line cl_args = CLI.parse() # Prints version of rss_reader and directory where it's placed if cl_args.get('version'): print(f"RSS-Reader {version}" + " from " + str(os.getcwd())) sys.exit() # Allow logger to print logs to command-line Logger().set_stream_logging(cl_args.get('verbose')) # Create logger by implemented function logger = Logger().get_logger("rss_reader") data = RSSDataHandler(*rss_handler(cl_args.get('source')), cl_args.get('json'), cl_args.get('limit')) output = OutputHandler(data, cl_args.get('colorize')) if cl_args.get('json'): pprint(unescape(output.format_to_json_string())) else: for text in output.format_news(): print(text, end="\n\n")
def test_too_many_arguments(self): """The method should recognize and raise an error if more than 2 arguments are given.""" test_args = ['choose', '3', '4'] CLI.file_set_cache = [self.test_set0, self.test_set1] with self.assertRaises( CLI.ArgumentAmountError, msg= "The method fails to recognize when too many arguments are given." ): CLI.choose(None, test_args) mock_assert_msg( mock_enumerate_sets.assert_not_called, [], "The method lists file sets even though an error was raised.")
def get_editor(cli, obj, name): editobj = get_editor_object(obj) if editobj is None: # not registered, try generic defaults if isinstance(obj, dict): cmd = cli.clone(CLI.DictCLI) elif hasattr(obj, "__dict__"): if isinstance(obj, netobjects.PersistentData): cmd = CLI.get_generic_clone(obj, cli, DataEditor) else: cmd = CLI.get_generic_clone(obj, cli, ObjectEditor) else: raise TypeError, "no editor available for %r." % (obj,) else: cmd = cli.clone(editobj) cmd._setup(obj, name) return cmd
def test_set_not_existent(self): "The method should recognize and raise an error when the given set number doesn't point to a FileSet." test_args = ['choose', '3'] CLI.file_set_cache = [self.test_set0, self.test_set1] with self.assertRaises( CLI.CLIRuntimeError, msg= "The method fails to recognize when a given file set number doesn't exist." ): CLI.choose(None, test_args) mock_assert_msg( mock_enumerate_sets.assert_not_called, [], "The method lists file sets even though an error was raised.")
def test_valid_existent_set_number(self): """The method should update the active file set if a valid set number is given.""" test_args = ['choose', '1'] CLI.file_set_cache = [self.test_set0, self.test_set1] CLI.choose(None, test_args) mock_assert_msg( mock_enumerate_sets.assert_not_called, [], "The method lists file sets even though a set number was supplied." ) self.assertEqual( CLI.active_file_set, self.test_set1, "The method fails to select the correct file set given the cache set number." )
def test_invalid_set_number(self): """The method should recognize and raise an error when the set number given is not a valid integer.""" test_args = ['choose', '2a'] CLI.file_set_cache = [self.test_set0, self.test_set1] with self.assertRaises( CLI.InputProcessingError, msg= "The method fails to recognize when an invalid integer is given as the set number." ): CLI.choose(None, test_args) mock_assert_msg( mock_enumerate_sets.assert_not_called, [], "The method lists file sets even though an error was raised.")
def win32(self, argv): """win32 <funcname> args... Calls the win32api function named <funcname> with the supplied arguments and return the results.""" funcname = argv[1] args, kwargs = CLI.breakout_args(argv[2:], vars(self._client)) rv = self._client.win32(funcname, *args, **kwargs) return rv
def test_load_config(self): with self.assertRaises(FileNotFoundError): CLI.load_config(None, None, 'bogus.ini') fake_ctx = mock.Mock() fake_ctx.params = { 'loglevel': 'CRITICAL', 'logfile': None, 'color': False } ret = CLI.load_config(fake_ctx, None, 'data/fake.ini') goodret = { 'gdrive': { 'folder_name': 'mypieye', 'client_id': '', 'client_secret': '' }, 'minsizes': { 'minsize': '1500', 'min_width': '100', 'min_height': '50' }, 'ignore': { 'trees': '(0, 0, 1980, 500)', 'lbush': '(648, 537, 448, 221)', 'rbush3': '(1601, 476, 188, 92)', 'rbush1': '(1715, 594, 177, 122)', 'rbush2': '(1716, 457, 75, 77)' }, 'savedir': 'd:/tmp/mypieye', 'credential_folder': '.', 'resolution': '720p', 'camera': '0', 'loglevel': 'DEBUG', 'logfile': '', 'color': 'True' } self.assertIsNotNone(ret) self.assertIsInstance(ret, dict) ret['gdrive']['client_id'] = '' ret['gdrive']['client_secret'] = '' self.assertDictEqual(goodret, ret)
def smtpcli(argv): """smtpcli [-h|--help] [-l|--logfile <logfilename>] [-s|--bindto <portname>] [host] [port] Provides an interactive session at a protocol level to an SMTP server. """ bindto = None port = 25 sourcefile = None paged = False logname = None try: optlist, args = getopt.getopt(argv[1:], "b:hp:s:l:g", ["bindto=", "help", "port=", "script=", "logfile="]) except getopt.GetoptError: print smtpcli.__doc__ return for opt, val in optlist: if opt == "-b" or opt == "--bindto": bindto = val if opt == "-l" or opt == "--logfile": logname = val elif opt == "-s" or opt == "--script": sourcefile = val elif opt == "-g": paged = True elif opt == "-h" or opt == "--help": print smtpcli.__doc__ return elif opt == "-p" or opt == "--port": try: port = int(val) except ValueError: print smtpcli.__doc__ return theme = CLI.DefaultTheme(PROMPT) parser = CLI.get_cli(EmailClientCLI, paged=paged, theme=theme) if len(args) > 0: if len(args) > 1: port = int(args[1]) else: port = 25 host = args[0] else: host = "" if logname: parser.commands.logfile(["logfile", logname]) if host: parser.commands.connect(["connect"]+IF(bindto, ["-s", bindto], [])+[host, port]) else: parser.commands._print("Be sure to run 'connect' before anything else.\n") if sourcefile: try: parser.parse(sourcefile) except CommandQuit: pass else: parser.interact()
def edit(self, argv): """edit <component> Interact with the specified component.""" name = argv[1] comp = getattr(self._obj, name) # component is property of base object cmd = CLI.get_generic_clone(comp, self) if cmd: raise NewCommand, cmd
def test_invalid_pattern(self): """The method should recognize and raise an error if the given pattern is invalid.""" test_args = ['create', 'new'] mock_expand_pattern.side_effect = CLI.PatternExpansionError( "Pattern expansion failed") with self.assertRaises( CLI.InputProcessingError, msg= "The method fails to recognize and raise an error when too few arguments are given." ): CLI.create(test_args) mock_assert_msg( mock_files_detected.assert_not_called, [], "The method creates a file set even though an error was raised.")
def _list_container(self, obj, indent=0, longopt=False): names = obj.keys() names.sort() if longopt: for name in names: val = obj[name] self._print("%s%20.20s : %s" % (" "*indent, name, CLI.safe_repr(val))) else: self._print_list(names, indent)
def test_multiple_sets(self): """The method should list all the sets if multiple of them have been found.""" test_set1 = FileSet(self.pattern, []) test_set2 = FileSet(('second', ''), []) test_set3 = FileSet(('x', 'y'), []) CLI.file_set_cache = [test_set1, test_set2, test_set3] CLI._enumerate_available_sets() assertion_calls = [ (mock_print.assert_any_call, [0, '\t', str(test_set1)]), (mock_print.assert_any_call, [1, '\t', str(test_set2)]), (mock_print.assert_any_call, [2, '\t', str(test_set3)]) ] mock_assert_many_msg( assertion_calls, "The method fails to list all of the multiple available file sets." )
def pass_parameters(self, path2, ip2, username2, password2): print(path2) self.file = open(path2, "w") print("opened file") time.sleep(30) self.txt = CLI.connection(ip2, username2, password2) time.sleep(30) for x in range(len(self.txt)): self.file.write(self.txt[x]) self.file.close() print("wrote")
def __init__(self, argv): """Pass the sys.argv parameter list to your __init__ method.""" # you must first inherit the super class __init__ method. super(Hello, self).__init__(argv) # add your Arguments self.user = CLI.List("user names") self.computer = CLI.Switch("name of the computer", "Lisa", "c", name="computer-name") self.message = CLI.Switch("the greeting", "how are you?", "m") self.verbose = CLI.Flag("show output", False, "v") self.version = CLI.Terminator("show version information", "hello.py (1.0.1)", "V") self.copyright = CLI.Terminator( "show copyright information", "hello.py (1.0.1)\n" "Copyright (c) Geoffrey Lentner 2015. All rights reserved.\n" "GNU General Public License (v3.0).\n" "This is free software; see the source for copyright conditions. There is NO\n" "waranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", "C") # if the `info` member is defined, it will be displayed at the end of a call to # -h | --help self.info = ("" "Report bugs to: [email protected]\n" "home page: <http://github.com/glentner/CLI-Python>")
def fiddle(self, argv): """fiddle <handle> fiddle with a remote file object. Provide the handle id obtained from 'flist'.""" args, kwargs = CLI.breakout_args(argv[1:], vars(self._client)) if args: handle = args[0] else: handle = self._client.flist()[0] finfo = self._client.get_handle_info(handle) if finfo: cmd = self.clone(FileCommand) cmd._setup(self._client, handle, "%s> " % (finfo,)) raise NewCommand, cmd # signal parser to use new cmd object else: self._print("No such handle on server.")
def interact(self, argv): """interact <pid> Interact with the raw file-like interface of a process. Provide the pid as supplied from plist.""" args, kwargs = CLI.breakout_args(argv[1:], vars(self._client)) if args: handle = int(args[0]) else: handle = self._client.plist()[0] pid = self._client.poll(handle) if pid: cmd = self.clone(ProcCommand) cmd._setup(self._client, pid, "pid %s> " % (pid,)) raise NewCommand, cmd # signal parser to use new cmd object else: self._print("No such pid on server.")
def remotecli(argv): """remotecli [-h|-?] [-g] [-s <script>] Provides an interactive session to a remote Client server object. Most of the methods in the module remote.Server may be called this way. """ #import testrunner import nmsgetopt import storage.Storage paged = False script = None try: optlist, longopts, args = nmsgetopt.getopt(argv[1:], "s:?hg") except GetoptError: print remotecli.__doc__ return for opt, val in optlist: if opt == "-?" or opt == "-h": print remotecli.__doc__ return elif opt == "-g": paged = True elif opt == "-s": script = val # do runtime setup cf = storage.Storage.get_config(initdict=longopts) #testrunner.connect_user(cf) #testrunner.runtime_config(cf) # fake test module attributes cf.reportfile = "remotecli" cf.logbasename = "remotecli.log" cf.arguments = argv theme = CLI.DefaultTheme(PROMPT) history=os.path.expandvars("$HOME/.hist_clientcli") parser = CLI.get_cli(TopLevelCLI, env=cf, paged=paged, theme=theme, historyfile=history) if script: try: parser.parse(script) except KeyboardInterrupt: pass else: parser.interact()
def configurator(self, argv): """configurator <device> Start an interactive `configurator` object on the current testbed.""" devname = argv[1] import configuratorCLI, configurator cf = self._obj._config dev = cf.devices.getpath(devname) if dev is None: self._print("No such device in storage.") return if not isinstance(dev, strataobjects._StrataDevice): self._print("Not a product object.") return ctor = configurator.get_configurator(dev, cf.logfile) cmd = CLI.get_generic_cmd(ctor, self._ui.clone(), configuratorCLI.ConfiguratorCLI) if cmd: raise NewCommand, cmd
def ls(self, argv): """ls [<obj>...] List contents of current container, or given containers.""" longopt = False optlist, longoptdict, args = self.getopt(argv, "l") for opt, arg in optlist: if opt == "-l": longopt = True if len(args) < 1: self._list_container(self._obj, longopt=longopt) else: matches = self._get_matchlist(args) for arg in matches: try: obj = self._obj[arg] except (KeyError, IndexError): self._print("No such object: %s" % (arg,)) else: if longopt: self._print("%20.20s : %s" % (arg, CLI.safe_repr(obj))) else: self._print(arg)
def _build_userinterface(self): name = self.get("userinterfacetype", "streaming") if name.startswith("stream"): import CLI return CLI.get_terminal_ui(env=self) elif name == "fullscreen": import cursesio return cursesio.get_curses_ui(env=self) elif name == "gtk": import gstratatest return gstratatest.get_ui(env=self) elif name == "production": import strataui return strataui.get_fancy_ui(env=self) elif name == "terse": import strataui return strataui.get_terse_ui(env=self) elif name == "tersestream": import strataui return strataui.get_tersestream_ui(env=self) else: raise ValueError, "Invalid user interface type specificed in 'userinterfacetype'."
def edit(self, argv): """edit <name> Interact with the named device.""" name = argv[1] obj = self._obj.get_object(name) if obj is None: self._print("No such device name. Choose from:") self._print_list(self._obj.keys()) return if hasattr(obj, "get_configurator"): self._print("Getting configurator. This may take a while...") obj = obj.get_configurator(self._obj._logfile) self._print("ok.") cmd = CLI.get_generic_cmd(obj, self._ui.clone(), configuratorCLI.ConfiguratorCLI) if cmd: raise NewCommand, cmd else: cmd = slstorageCLI.get_editor(self, obj, obj.name) if cmd: raise NewCommand, cmd else: self._print("No editor for %r." % (obj,))
def configurator_cli(argv): """configurator_cli [-s <script>] [-g] [<device>] Interact with a device configurator. Options: -g Use paged output (like 'more') -s <script> Run a CLI script from the given file instead of entering interactive mode. """ import os import configurator import stratatestrunner import slstorage as Storage import nmsgetopt paged = False script = None try: optlist, longopts, args = nmsgetopt.getopt(argv[1:], "s:?g") except GetoptError: print configurator_cli.__doc__ return for opt, val in optlist: if opt == "-?": print configurator_cli.__doc__ return elif opt == "-g": paged = True elif opt == "-s": script = val if len(args) >= 1: devname = args[0] else: print configurator_cli.__doc__ return if paged: import termtools io = termtools.PagedIO() else: io = CLI.ConsoleIO() cf = Storage.get_config(initdict=longopts) stratatestrunner.runtime_config(cf) # fake test module attributes cf.reportfile = "configurator_cli" cf.logbasename = "configurator_cli.log" cf.arguments = argv dev = cf.devices.getpath(devname) if dev is None: print "Could not find that device." return ctor = dev.get_configurator(cf.logfile) # construct the CLI theme = ConfiguratorTheme("Configurator> ") ui = CLI.UserInterface(io, cf, theme) cmd = CLI.get_generic_cmd(ctor, ui, ConfiguratorCLI) parser = CLI.CommandParser(cmd, historyfile=os.path.expandvars("$HOME/.hist_configurator")) try: if script: try: parser.parse(script) except KeyboardInterrupt: pass else: parser.interact() finally: ctor.close() del cf.logfile
from org.jboss.as.cli.scriptsupport import CLI cli = CLI.newInstance() cli.connect() cli.cmd("cd /core-service=platform-mbean/type=memory/") result = cli.cmd(":read-resource(recursive=false,proxies=false,include-runtime=true,include-defaults=true)") response = result.getResponse() enabled = response.get("result").get("heap-memory-usage") used = enabled.get("used").asInt() if used > 512000000: print "Over 1/2 Gb Memory usage " else: print 'Low usage!' cli.disconnect()
if __name__ == "__main__": # Dit stuk regelt de CLI options from sys import stderr import CLI,sys my_opts = [ # short, long, args, description ('t','tensor',0,"zet tensor aan"), ('w','wavelet',1,"select wavelet <arg>"), ('s','smooth',0,"select quadratic thresholding"), ('c','compress',1,"set compression to <arg>"), ('o','output',1,"set destination to <arg>"), ('d','delay',1,"set frame-delay to <arg>"), ('h','help',0,'print this message') ] my_usage = CLI.usage("python animated_gif.py [gif] [options]", "Uses various wavelets to compress and then decompress an animated gif", my_opts) try: args, opts = CLI.parse_args(sys.argv,my_opts) #throws IOError on error except IOError: print my_usage.short() exit(1) #set defaults for various options from Wavelet_Defs import wavelet_dict mywavelet = wavelet_dict['haar'] mycompress = 1.0 myoutfile = None mytensor = False mydelay = 10 mythreshfunc = threshold_hard
def get_tersestream_ui(env=None): return CLI.get_ui(CLI.ConsoleIO, TerseStreamInterface, env=env)
print "saving to",filename mat3img(sliced,dim).save(filename) if __name__=="__main__": # Dit stuk regelt de CLI options from sys import stderr import CLI,sys my_opts = [ # short, long, args, description ('s','smooth',0,"activate quadratic threshold"), ('c','compress',1,"set compression to <arg>"), ('o','output',1,"set destination to <arg>"), ('h','help',0,'print this message') ] my_usage = CLI.usage("3chan.py [picture] [options]", "Uses various wavelets to compress and then decompress a picture", my_opts) try: args, opts = CLI.parse_args(sys.argv,my_opts) #throws IOError on error except IOError: print my_usage.short() exit(1) #set defaults for various options from Wavelet_Defs import wavelet_dict mycompress = 1.0 myoutfile = None for o in opts: if o[0] == 'compress': try:
float(psnr_haar[c]),float(psnr_db2[c])) print >>f,"\\end{array}" if __name__=="__main__": from sys import stderr import CLI,sys my_opts = [ # short, long, args, description ('p','psnr',0,'skips to PSNR calc'), ('t','tensor',1,'tensor ja/nee ja!'), ('i','infile',1,"set infile to <arg>"), ('h','help',0,'print this message') ] my_usage = CLI.usage("maek_graphics.py [-i picture] <compressions>", "Makes fancy gaphics", my_opts) try: args, opts = CLI.parse_args(sys.argv,my_opts) #throws IOError on error except IOError: print my_usage.short() exit(1) from Wavelet_Defs import wavelet_dict mytensor = False myinfile = None myskip = False for o in opts: if o[0] == 'tensor': mytensor = True
def __init__(self, syslog, ps1="syslog> "): self.syslog = syslog theme = CLI.DefaultTheme(ps1) self.parser = CLI.get_cli(SyslogCLI, paged=False, theme=theme, aliases=_CMDALIASES) self.parser.command_setup(syslog, ps1)
for fname in NAMETOOBJECT.keys(): try: os.link("genericcli.py", fname) except OSError, why: if why[0] == EEXIST: pass else: raise else: print "linked genericcli.py as %s. You man now invoke that command." % (fname,) def main(argv): path, basename = os.path.split(argv[0]) cname = NAMETOOBJECT.get(basename, None) if cname is None: print "Did not find key %s, making links." % (basename,) make_links() else: try: klass = _get_object(cname) except ValueError, err: print err print "Using generic CLI." CLI.run_generic_cli() else: print "Wrapping class %s." % (klass.__name__,) CLI.run_cli_wrapper(argv, klass) main(sys.argv)