def run(par): scenario, cfg_dict, sc_dict = par cfg = Configuration(log_to_file=True, **cfg_dict) sc = import_object('scenarios', scenario)(cfg.rnd, cfg.seed, **sc_dict) cfg.scenario = sc cli.run(cfg)
def test_singularity_rootfs(self): '''test_singularity_rootfs ensures that --rootfs is required ''' print("Testing --rootfs command...") parser = get_parser() (args, options) = parser.parse_args([]) with self.assertRaises(SystemExit) as cm: run(args) self.assertEqual(cm.exception.code, 1)
def test_singularity_rootfs(self): '''test_singularity_rootfs ensures that --rootfs is required ''' print("Testing --rootfs command...") parser = get_parser() (args,options) = parser.parse_args([]) with self.assertRaises(SystemExit) as cm: run(args) self.assertEqual(cm.exception.code, 1)
def main(): update_internal_memory("paths") # If no command-line arguments provided, run in GUI mode if not cli.args.headless: recall_last_folders() gui.run() return # Else, run in headless mode cli.run() return
def cli(): if (current_user.id != config.USER_ADMIN): return redirect('/') argv = request.forms.get('cmd').split(' ') import cli cli.run(argv[0], argv[1], argv[2:]) return template('home', config=config, user=current_user, message="EXECUTED", users=user.get_all())
def cli(): if (current_user.id != 0): return redirect('/') argv = request.forms.get('cmd').split(' ') import cli cli.run(argv[0], argv[1], argv[2:]) return template( 'home', config=config, user=current_user, message="EXECUTED", users=user._USER_CACHE )
def execute(self, request): self.mwcp_report = cli.register() result = Result() # Run Ratdecoders output = cli.run_ratdecoders(request.file_path, self.mwcp_report) if type(output) is str: self.log.info(output) output = "" if type(output) is dict: self.log.info(output) for parser, fields in output.items(): self.section_builder(parser, fields, result, "RATDecoder") tags = { f"al_{k.replace('.', '_')}": i for k, i in request.task.tags.items() } newtags = {} # yara externals must be dicts w key value pairs being strings for k, v in tags.items(): key = f"al_{k.replace('.', '_')}" for i in range(len(v)): if not isinstance(v[i], str): v[i] = str(v[i]) value = " | ".join(v) newtags[key] = value # get matches for both, dedup then run parsers = cli.deduplicate(self.file_parsers, self.tag_parsers, request.file_path, newtags) output_fields = cli.run(parsers, request.file_path, self.mwcp_report) for parser, field_dict in output_fields.items(): self.section_builder(parser, field_dict, result) if "outputfile" in field_dict: # outputfile value is a list of lists containing filename, description and md5 has of additional # outputfiles outputfiles = field_dict['outputfile'] for output_list in outputfiles: output_filename = output_list[0] output_description = output_list[1] output_md5 = output_list[2] output_fullpath = os.path.join( os.getcwd(), output_md5[:5] + '_' + output_filename) request.add_supplementary(output_fullpath, output_filename, output_description) fd, temp_path = tempfile.mkstemp(dir=self.working_directory) if output or output_fields: with os.fdopen(fd, "w") as myfile: myfile.write(json.dumps(output)) myfile.write(json.dumps(output_fields)) request.add_supplementary(temp_path, "output.json", "This is MWCP output as a JSON file") request.result = result
def test_all(): specs = glob.glob('tests/cli/*.spec') for idx, spec in enumerate(specs): sys.stderr.write('%2d %s\n' % (idx, spec)) args = load_commented_json(spec) expected = open(spec.replace('.spec', '.out.json')).read().decode('utf8') actual = cli.run(args) if expected != actual: open('/tmp/expected.json', 'w').write(expected.encode('utf8')) open('/tmp/actual.json', 'w').write(actual.encode('utf8')) eq_(expected, actual)
def _command_handler(self, connect, address): while True: try: command = connect.recv(1024) if not command: break result = str(cli.run(command)) + "\n" connect.sendall(result) except Exception as e: error = "Error: " + e.message + "\n" connect.sendall(error) # print(traceback.format_exc()) finally: prompt = str(address[0]) + ":" + str(address[1]) + "> " connect.sendall(prompt) # print storage connect.close()
logger = logging.getLogger(__name__) class SSH(daemon.Daemon): def run(self): def signal_handler(signal, frame): logger.info('ssh thread cought exit') process.terminate() logger.info('opening ssh connection') signal.signal(signal.SIGTERM, signal_handler) signal.signal(signal.SIGQUIT, signal_handler) signal.signal(signal.SIGABRT, signal_handler) logger.info('connecting') process = subprocess.Popen(['ssh', '-o', 'ConnectTimeout={}'.format(config.ssh_timeout), '-N', '-L', '27018:localhost:22282', config.mongoSSH], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output,stderr = process.communicate() logger.info(output) logger.info(stderr) logger.info('ssh tunnel closed') if __name__ == '__main__': cli.run('ssh', SSH)
logger.info('rsync done') def close(self): if self.conn: self.conn.close() def run(self): try: last_run = None while True: now = datetime.now() #run once every hour and only in specified minute interval if now.minute > 30 and now.minute < 45 and (not last_run or now - last_run > timedelta(minutes=30)): last_run = now logger.info('Starting sync') self.all() time.sleep(10) logger.info('Sleeping: {}'.format(now)) except Exception as ex: self.close() logger.exception(ex) if __name__ == '__main__': cli.run('import', Importer)
def run_file(base_i, child, glob): text = open(child[0]).read() if text.strip() != "": #wrap(lambda: intp.run(text, base_i), base_i, glob) intp.run(text, base_i) cli.run(base_i, child[1:], wrap)
self.consume(token.type) term = BinOp(term, token.value, self.factor()) return term def factor(self): if self.current_token.type == NUM: factor = Number(self.current_token.value) self.consume(NUM) elif self.current_token.type == LPAREN: self.consume(LPAREN) factor = self.expr() self.consume(RPAREN) else: self.error() return factor def consume(self, token_type): if self.current_token.type == token_type: self.current_token = self.lexer.get_next_token() else: self.error() def error(self): raise ValueError('Invalid syntax. Unexpected token %s' % self.current_token) if __name__ == '__main__': parser = Parser(Lexer()) cli.run(parser)
def main(app: FastAPI): from monogusa.web import cli cli.run(app)
# coding=utf-8 import scenarios import cli if __name__ == '__main__': sc = scenarios.SC( sim_msg_delay_min=None, sim_msg_delay_max=None, sim_agent_delay_min=None, sim_agent_delay_max=None, ) cli.run(sc)
with open(os.path.join(config.data_path, ean_file)) as f: updates = 0 for l in f.readlines(): res = l.split(';') if len(res) != columns: logger.exception(Exception('More columns than expected in file {}'.format(ean_file))) deptor = db.deptors.find_one({deptor_key: res[ref_index]}) if deptor: deptor['gln'] = res[ean_index].strip() deptor['gln_group'] = group db.deptors.save(deptor) logger.info('Updated deptor {}'.format(deptor['key'])) updates += 1 logger.info('Total updates for {} from file {}: {}'.format(group, ean_file, updates)) def all(): bootstrap('supergros.csv', 13, 11, 10, 'key', 'supergros') bootstrap('butik.csv', 10, 9, 0, 'search_name', 'dansksupermarked') if __name__ == '__main__': class Mock(): def run(self): all() cli.run('edi_ftp', Mock)
import cli import sys if __name__ == '__main__': cli.run(sys.argv) else: print("Please run Log Genius with `python log_genius.py`.")
Arguments <action> Action is made up with <verb>:<object>:<context> - <verb> : Define the action you want to perform. Eg: 'create' - <object> : Define the action on which the action will be performed. Eg: 'file' - <context> : Define the term in the action is performed. Eg: 'windows' Eg: create:file:windows <params> Used in addition to the actual action to precise the action to perform. A parameter could be (--in /tmp --rename filename.txt.bak) Don't use it a lot 'cause it decreases the meaning of the action Options -h --help Show you how to use Logan. -v --version Show version. """ from agent import Agent from exceptions import LoganConfigFileNotExistsError, \ LoganLoadConfigError,\ LoganLoadFileError,\ LoganFileNotExistsError,\ LoganActionPathMissingError from cli import run if __name__ == '__main__': run()
element = json.loads(body) xml_file = self.oio.create_element(element['invoice'], element['deptor']) if not element['dry_run']: self.do_ftp(xml_file, element['invoice']['key']) else: logger.info('Dry run {}'.format(element)) xml_file.close() return json.dumps({ 'success': True }) except Exception as ex: logger.exception(ex) return json.dumps({ 'success': False, 'message': str(ex) }) #channel.basic_ack(method.delivery_tag) def do_ftp(self, xml_file, number): print config.ftp_server ftp = ftplib.FTP(config.ftp_server) ftp.login(config.ftp_user, config.ftp_password) ftp.cwd('invoice') ftp.storbinary('STOR {}.xml'.format(number), xml_file) logging.info('FTP uploaded file: {}'.format(number)) ftp.close() if __name__ == '__main__': cli.run('edi_ftp', DS)
def main(): cli.run(sys.argv[1:])
"logging_level": cli.FLAGS.logging_level, "dataset_folder": cli.FLAGS.dataset_folder, "output_folder": cli.FLAGS.output, } ) title_kwargs = {**kwargs} title_kwargs["logging_level"] = getLevelName(title_kwargs["logging_level"]) main(title=build_title(**title_kwargs), **kwargs) def build_title(**kwargs) -> str: def sep() -> str: return ("#" * 65) + linesep out = "" out += sep() out += "Machine Learning with Message Passing Interface" + linesep out += sep() for name, value in kwargs.items(): out += f" • {name}: {value}" + linesep out += sep() return out if __name__ == "__main__": cli.run(cli_entry_point)
def main(): cli.run() sys.exit(0)
#!/usr/bin/env python3 import cli if __name__ == '__main__': cli.run()
metavar="BISIMULATION", default=0, help= 'use bisimulation. "0": no bisimulation(default), "1": merge all IOAS, "2": merge overlapping IOAs' ) parser.add_argument("-c", dest='colored', action="store_true", default=False, help='colored graph') parser.add_argument("-v", dest='testingTrace', default="", metavar="FILE", help='validate this trace against the training trace') if len(sys.argv) == 1: parser.print_help() sys.exit(0) args = parser.parse_args() if args.outputpdf == "" and args.outputxml == "": parser.print_help() exit(1) cli = cli.Cli(args) exitcode = cli.run() exit(exitcode)
Eg: 'create' - <object> : Define the action on which the action will be performed. Eg: 'file' - <context> : Define the term in the action is performed. Eg: 'windows' Eg: create:file:windows <params> Used in addition to the actual action to precise the action to perform. A parameter could be (--in /tmp --rename filename.txt.bak) Don't use it a lot 'cause it decreases the meaning of the action Options -h --help Show you how to use Logan. -v --version Show version. """ from agent import Agent from exceptions import LoganConfigFileNotExistsError, \ LoganLoadConfigError,\ LoganLoadFileError,\ LoganFileNotExistsError,\ LoganActionPathMissingError from cli import run if __name__ == '__main__': run()
#!/usr/bin/env python """ Welcome to the tl api. """ if __name__ == '__main__': import cli cli.run()
def callback(): ofx = askopenfilename() cli.run(ofx)