def auto_complete(): cli = Cli() complete = get_best_completions.Complete() input_ = cli.input() while input_ != QUIT_REQUEST: cli.output(complete.get_best_completions(input_)) input_ = cli.input()
def start(): core.file.SEARCH_PATH = os.getcwd() os.chdir(os.path.abspath(os.path.dirname(__file__))) control = Control() instance = Cli(control) #controller.register_view(instance, Attributes.CLI_ATTRIBUTES) instance.start()
def __init__(self, should_perform_task_setup=True): from logger import log self.cli = Cli() # want some help self.cli.show_and_exit_on_help_request() # load/import task module self.task = self.cli.load_command() # get command specific args self.command_args = self.cli.get_command_args() # get global args self.global_args = self.cli.get_global_args() if should_perform_task_setup: # set log level if self.global_args['--debug']: log.setLogLevel(logging.DEBUG) else: log.setLogLevel(logging.INFO) # set log file if self.global_args['--logfile']: log.set_logfile( self.global_args['--logfile'] )
def __init__(self, config, message_cb): # print MAC, set MAC is given and restart self.config = config self.mesh = MeshInterface(self.config, message_cb) self.kill_all = False self.deepsleep_timeout = 0 self.new_lora_mac = None # self.mesh.statistics.sleep_function = self.deepsleep_init self.mesh.sleep_function = self.deepsleep_init self.cli = Cli(self.mesh, self) self.cli.sleep = self.deepsleep_init self.is_paused = False self._threads_start() _thread.start_new_thread(self.cli.process, (1, 2)) self.ble_rpc = None if config.get("ble_api", False): try: from ble_rpc import BleRpc except: from _ble_rpc import BleRpc self.ble_rpc = BleRpc(self.config, self.mesh)
def test_run_write(self): spy = mock.Mock(wraps=Feed()) cli = Cli(spy) cli.run(self.josh_hello_cmd) spy.post_message.assert_called_once_with(username="******", message="Hello!") spy.get_messages_of.assert_not_called()
def __init__(self): self.state = MainAppState.INIT self.display = Display() self.ee = BaseEventEmitter() self.cli = None if Config.ENABLE_CLI: self.cli = Cli()
def test_get_all_arguments(self): cli = Cli() with patch.object(sys, 'argv', ["prog", "something", 4]): assert cli.get_all_arguments() == ["prog", "something", 4], "wrong user parameters getting" with patch.object(sys, 'argv', ["prog"]): assert cli.get_all_arguments() == ["prog"], "wrong user parameters getting" with patch.object(sys, 'argv', []): assert cli.get_all_arguments() == [], "wrong user parameters getting"
def cli(*args): cli = Cli(os.environ.get('ATOMIX_HOST', 'localhost'), int(os.environ.get('ATOMIX_PORT', 5678))) try: if len(args) > 0: cli._process_command(*args) else: cli.run() except (EOFError, KeyboardInterrupt): cli.set_return_value(None)
def test_defaults(self): cli = Cli() opt, vls = cli.parse() self.assertEquals(opt.message, '') self.assertEquals(opt.soundfile, None) self.assertEquals(opt.exitat, 5) self.assertEquals(opt.timeline, False) self.assertEquals(opt.fullscreen, False) self.assertEquals(opt.alarm, False)
def main(): """ The main function executes the program """ logging.config.fileConfig(LOG_CONF) cli = Cli() cli.parse_arguments_advanced() try: ret = cli.args_handel() if ret[0] == Cmd.invalid_input: sys.exit("invalid input") logging.debug(f'Arguments received: {ret}') except Exception as ex: logging.error(f'Failed to handel args, error: {ex}') sys.exit("invalid input") sc = Scrapping() cat = ret[1] sub_cats = ret[2] exist_cat = sc.get_category_list(URL) logging.debug(f'List of categories: {exist_cat}') if ret[0] == Cmd.cat_list: print(exist_cat) elif ret[0] == Cmd.sub_cat_list: if cat not in exist_cat: logging.error(f'Invalid input: category {cat} not exists') sys.exit("invalid input") cat_link = sc.get_category_links(URL, cat) sub_category_list = sc.get_category_list(cat_link[cat]) print(sub_category_list) elif ret[0] == Cmd.write_to_db: if cat not in exist_cat: logging.error(f'Invalid input: category {cat} not exists') sys.exit("invalid input") cat_link = sc.get_category_links(URL, cat) exist_subcat = sc.get_category_list(cat_link[cat]) if set(sub_cats) - set(exist_subcat) != set(): logging.error(f'Invalid input: at least on of subcategories {sub_cats} not exists') sys.exit("invalid input") cat_link = sc.get_category_links(URL, cat) sub_cat_links = sc.get_category_links(cat_link[cat], sub_cats) recipes = {} for sub_cat, link in sub_cat_links.items(): recipes[sub_cat] = sc.get_recipe_links(link) logging.debug(f'Scrap for categories: {cat}, and sub-categories: {sub_cat}') data_sc = sc.scrap_data(cat, recipes) api = API() data_api = api.get_info_ingred() sc.write_data_to_csv(data_sc, REC_FILENAME, RECIPE_DETAILS) sc.write_data_to_csv(data_api, ING_FILENAME, ING_DETAILS) db = DataBase(DB_HOST, DB_USER, DB_PASSWD, DB_NAME) db.write_data_to_db(data_sc, data_api)
def run(args): cli = Cli("example") num1 = int(args["NUM1"]) num2 = int(args["NUM2"]) total = num1 + num2 total_minus_one = total - 1 logger.info(f"{num1} plus {num2} is {total}") logger.info(f"minus 1 that's {total_minus_one}") logger.warn("QUICK MATHS")
def test_get_rest_arguments(self): cli = Cli() cli.user_arguments = ["script_name", "arg1"] assert cli.get_rest_arguments() == [], "empty list should be returned (two parameters)" cli.user_arguments = ["smth", "arg1", "arg2", "arg3"] assert cli.get_rest_arguments() == ["arg2", "arg3"], "[arg2, arg3] should be returned" cli.user_arguments = ["bla"], assert cli.get_rest_arguments() == [], "empty list should be returned (one parameter)" cli.user_arguments = [], assert cli.get_rest_arguments() == [], "empty list should be returned (no parameters)" cli.user_arguments = ["smth", "arg1", "arg2"] assert cli.get_rest_arguments() == ["arg2"], "[arg2] should be returned"
def main(): global SONM_CLI SONM_CLI = Cli(set_sonmcli()) global INTERVIEWED_WORKERS INTERVIEWED_WORKERS = [] global DEAD_WORKERS DEAD_WORKERS = [] global CURL CURL = "curl -s https://dwh.livenet.sonm.com:15022/DWHServer/GetOrders/ -d" global ORDERS_FOR_REMOVAL ORDERS_FOR_REMOVAL = [] global DEALS DEALS = [] workers_count, workers_addrs = get_orders() print("========= Checking worker status ==========") for address in workers_addrs: threading.Thread(target=check_worker, kwargs={ 'address': address }).start() time.sleep(1) # waiting for all workers to be interviewed while len(INTERVIEWED_WORKERS) < workers_count: time.sleep(1) print("=========== Bad guys (" + str(len(DEAD_WORKERS)) + ") are: ===========") for i in DEAD_WORKERS: print(i) print("====== Gathering orders for removal ======") for address in DEAD_WORKERS: threading.Thread(target=get_orders_for_bad_suppliers, kwargs={ 'supplier': address }).start() time.sleep(3) print("TOTAL Orders for removal: " + str(len(ORDERS_FOR_REMOVAL))) print("======== Removing orders... ========") for order in ORDERS_FOR_REMOVAL: threading.Thread(target=open_deal, kwargs={'order': order}).start() time.sleep(1) while True: if len(DEALS) == len(ORDERS_FOR_REMOVAL): break total_spendings = calc_expanses() print("=====================" + "\n" + "Total spendings: " + str(total_spendings) + " SNM")
def main(argv): _, mode, starter, emule = ["main.py", "pc", "1", "1"] emule = bool(int(emule)) # '0' -> 0 -> False # '1' -> 1 -> True starter = int(starter) g = Game(bool(emule), mode) c = Cli(g) game = Thread(target=g.run, args=(starter,)) cli = Thread(target=c.run) game.start() cli.start()
def __init__(self): """Member variables will be cli """ self.deploy = run_deploy self.monitor = run_monitor self.cluster = Cluster() self.thriftserver = ThriftServer() self.ll = log.set_level self.cli = Cli() self.passwd = run_passwd self.adduser = run_adduser self.import_conf = run_import_conf self.sql = run_fbsql self.c = run_cluster_use self.edit = run_edit self.delete = run_delete
def test_if_have_just_those_options(self): cli = Cli() opt, vls = cli.parse() #FIXME: need to find another way to test if 'Cli' just have that options self.assertEquals( opt, { 'fullscreen': False, 'message': '', 'exitat': 5, 'soundfile': None, 'timeline': False, 'debug': False, 'alarm': False, 'color': '' })
def main(argv): opts = None try: opts, args = getopt.getopt( argv[1:], 'hcsa:u:p:', ["help", "client", "server", "app=", "user="******"password="******"unhandled option" if server: conf = {'/': {'tools.sessions.on': True}} cherrypy.quickstart( SafeBox(os.environ['DB_KEY'], os.environ['MASTER_PASSWORD']), '/', conf) elif client: check_arg(app, "app is required") cli = Cli('http://localhost:8080') if user is None and password is None: cli.get(app) else: check_arg(user, "username of app required") check_arg(password, "password of app required") cli.save(app, user, password)
def test_get_first_arg(self): cli = Cli() cli.user_arguments = ["script_name", "arg1"] assert cli.get_first_arg() == "arg1" cli.user_arguments = ["smth", "arg1", "arg2", "arg3"] assert cli.get_first_arg() == "arg1", "[arg1] should be returned" cli.user_arguments = ["bla"] try: cli.get_first_arg() self.fail("Exception should be thrown") except NameError as e: assert str(e) == "ERROR: You have to specify at least alg id!" cli.user_arguments = [] try: cli.get_first_arg() self.fail("Exception should be thrown") except NameError as e: assert str(e) == "ERROR: You have to specify at least alg id!"
def main(ctx, hosts, debug): """A Powerful Zookeeper Client Tool.""" cli = None try: # 解析参数 config = parse_config(hosts=hosts, debug=debug) # 创建客户端 cli = Cli(config=config) cli.connect() log.banner() # 进入交互界面 loop_prompt(cli, config) except Exception as e: log.error(e) ctx.exit(code=1) finally: if cli: cli.quit() log.info('BYE!')
def test_parameters(self): cli = Cli() parser = cli.get_parser() self.assertTrue(parser.has_option("-m")) self.assertTrue(parser.has_option("--message")) self.assertTrue(parser.has_option("-s")) self.assertTrue(parser.has_option("--soundfile")) self.assertTrue(parser.has_option("-e")) self.assertTrue(parser.has_option("--exitat")) self.assertTrue(parser.has_option("-t")) self.assertTrue(parser.has_option("--timeline")) self.assertTrue(parser.has_option("-f")) self.assertTrue(parser.has_option("--fullscreen")) self.assertTrue(parser.has_option("-a")) self.assertTrue(parser.has_option("--alarm"))
def __init__(self, config, message_cb): # print MAC, set MAC is given and restart self.config = config self.mesh = MeshInterface(config, message_cb) self.kill_all = False self.deepsleep_timeout = 0 self.new_lora_mac = None # watchdog = Watchdog(meshaging, mesh) self.mesh.statistics.sleep_function = self.deepsleep_init self.mesh.sleep_function = self.deepsleep_init self.cli = Cli(self.mesh) self.cli.sleep = self.deepsleep_init _thread.start_new_thread(self.process, (1, 2)) _thread.start_new_thread(self.cli.process, (1, 2)) self.ble_rpc = None if config.get("ble_api", False): self.ble_rpc = BleRpc(self.config, self.mesh)
def test_e2e(self): cli = Cli(Feed()) cmds = [ "Josh -> As Josh used to say", "Josh", "Josh follows Bob", "Bob -> @Josh whats'up?", "John -> pancakes", "Bob -> @John you cooking pancakes?", "Josh -> mamma mia", "Josh wall", ] parsed = [cli.parse(cmd) for cmd in cmds] run = [cli.run(cmd) for cmd in parsed] expected = [ "mamma mia", "@John you cooking pancakes?", "@Josh whats'up?", "As Josh used to say", ] self.assertEqual(expected, run[-1])
def main(): args = get_args() cmd = Cli() result = getattr(cmd, args.command)(*args.args) pprint(result)
def deepsleep_init(timeout, new_MAC=None): """ initializes an deep-sleep sequence, that will be performed later """ global deepsleep_timeout, kill_all, new_lora_mac deepsleep_timeout = timeout kill_all = True if new_MAC: new_lora_mac = new_MAC return mesh.statistics.sleep_function = deepsleep_init mesh.sleep_function = deepsleep_init cli = Cli(mesh, rpc_handler, ble_comm) cli.sleep = deepsleep_init _thread.start_new_thread(cli.process, (1, 2)) try: while True: if kill_all: deepsleep_now() time.sleep(.1) pass except KeyboardInterrupt: print('Got Ctrl-C') except Exception as e:
elif args.file is not None: args.dirname, args.filename = os.path.split(args.file) if error is not None: print "Error: {}".format(error) parser.exit(1) return isGui, (args) if __name__ == '__main__': print APP_NAME + "\n" if 'rtlsdr_update_timestamp'in os.environ: set_version_timestamp() isGui, args = __arguments() if isGui: app = RtlSdrScanner() app.SetClassName(APP_NAME) wx.Locale().Init2() frame = FrameMain(APP_NAME) if args.file is not None: frame.open(os.path.abspath(args.dirname), args.filename) app.MainLoop() else: try: Cli(args) except KeyboardInterrupt: print '\nAborted' exit(1)
if error is not None: print "Error: {}".format(error) parser.exit(1) return isGui, (args) if __name__ == '__main__': multiprocessing.freeze_support() pool = multiprocessing.Pool(initializer=__init_worker) print APP_NAME + "\n" if 'rtlsdr_update_timestamp'in os.environ: set_version_timestamp() isGui, args = __arguments() if isGui: app = RtlSdrScanner(pool) app.SetClassName(APP_NAME) wx.Locale().Init2() frame = FrameMain(APP_NAME, pool) if args.file is not None: frame.open(os.path.abspath(args.dirname), args.filename) app.MainLoop() else: try: Cli(pool, args) except KeyboardInterrupt: print '\nAborted' exit(1)
def __init__(self): super().__init__() self.__interface = Cli() self.__database = Database("database.txt")
def __init__(self): self.cli = Cli() self.logger = Logger(self.cli.get_arg('verbosity_level'))
from Todolist import ToDoList from cli import Cli if __name__ == "__main__": """This is the main function which runs the CLI. """ cli = Cli() cli.run_cli()
def refresh(self): self._crontab = CronTab('root') self._cli = Cli() self._load()