def main(): sys.stdout = sys.stderr try: opts, rest = getopt.getopt(sys.argv[1:], 'h:p:d:qvL') if not rest: cmd = 'head' else: cmd, rest = rest[0], rest[1:] if cmd not in commands: raise getopt.error("unknown command") coptset, func = commands[cmd] copts, files = getopt.getopt(rest, coptset) except getopt.error as msg: print(msg) print("usage: rrcs [options] command [options] [file] ...") print("where command can be:") print(" ci|put # checkin the given files") print(" co|get # checkout") print(" info # print header info") print(" head # print revision of head branch") print(" list # list filename if valid") print(" log # print full log") print(" diff # diff rcs file and work file") print("if no files are given, all remote rcs files are assumed") sys.exit(2) x = openrcsclient(opts) if not files: files = x.listfiles() for fn in files: try: func(x, copts, fn) except (IOError, os.error) as msg: print("%s: %s" % (fn, msg))
def test_long_1arg_novalue(self): # first argument is the args that have been read in. this would be # replaced by sys.argv in normal operation # second argument is the validation rules, so in this case we should expect # 1 type of option with no value rules = ['noarg'] validargs = ['--noarg'] options,remainder = getopt(['--noarg'],'',rules) for option, value in options: self.assertIn(option,validargs) # its also valid to pass in no arg options,remainder = getopt([],'',rules) for option, value in options: self.assertIn(option,validargs) # but will fail if an unknown arg is passed in with self.assertRaises(GetoptError): options,remainder = getopt(['--foobar'],'',rules) # but will fail if a value for option is passed in with self.assertRaises(GetoptError): options,remainder = getopt(['--noarg=foobar'],'',rules)
def main(my_argv): inputfile = '' revision = None if (len(my_argv) <= 3): try: opts, args = getopt.getopt(my_argv,"i:",["ifile="]) except getopt.GetoptError: print 'Usage: Wikiwho_simple.py -i <inputfile> [-rev <revision_id>]' exit(2) else: try: opts, args = getopt.getopt(my_argv,"i:r:",["ifile=","revision="]) except getopt.GetoptError: print 'Usage: Wikiwho_simple.py -i <inputfile> [-rev <revision_id>]' exit(2) for opt, arg in opts: if opt in ('-h', "--help"): print "WikiWho: An algorithm for detecting attribution of authorship in revisioned content" print print 'Usage: Wikiwho_simple.py -i <inputfile> [-rev <revision_id>]' print "-i --ifile File to analyze" print "-r --revision Revision to analyse. If not specified, the last revision is printed." print "-h --help This help." exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-r", "--revision"): revision = arg return (inputfile,revision)
def main(my_argv): inputfile = '' revision = None if (len(my_argv) == 0): print 'Usage: Wikiwho.py -i <inputfile> [-rev <revision_id>]\n' exit(2) elif (len(my_argv) <= 2): try: opts, args = getopt.getopt(my_argv,"i:",["ifile="]) except getopt.GetoptError: print 'Usage: Wikiwho.py -i <inputfile> [-r <revision_id>]\n' exit(2) else: try: opts, args = getopt.getopt(my_argv,"i:r:",["ifile=","revision="]) except getopt.GetoptError: print 'Usage: Wikiwho.py -i <inputfile> [-r <revision_id>]\n' exit(2) for opt, arg in opts: if opt in ('-h', "--help"): help() exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-r", "--revision"): revision = arg return (inputfile,revision)
def parseargs(): global cmdLineArgs, cmdLineArgsHelp for i, arg in enumerate (sys.argv): sys.argv [i] =arg.replace ('\\', '/') args =[] argsSt ='' for i in cmdLineArgsHelp.keys (): if cmdLineArgsHelp [i] [1] == '': args.append (i) argsSt +=i [:1] else: args.append (i + '=') argsSt +=i [:1] + ':' opts, unused_args =getopt.getopt (sys.argv [1:], argsSt, args) # Debugging in Eclipse on the Mac add a second argument in sys.argv if len (opts) == 0: opts, unused_args =getopt.getopt (sys.argv [2:], argsSt, args) # End of Debugging in Eclipse trick cmdLineArgs ['debug'] =False for o, a in opts: if o in ('-h', '--help'): usage () sys.exit () if o in ('-d', '--debug'): cmdLineArgs ['debug'] =True else: cmdLineArgs [o[2:]] =a # Add a trailing slash to the source directory cmdLineArgs ['source'] +='/'
def main(): sys.stdout = sys.stderr try: opts, rest = getopt.getopt(sys.argv[1:], 'h:p:d:qvL') if not rest: cmd = 'head' else: cmd, rest = rest[0], rest[1:] if not commands.has_key(cmd): raise getopt.error, "unknown command" coptset, func = commands[cmd] copts, files = getopt.getopt(rest, coptset) except getopt.error, msg: print msg print "usage: rrcs [options] command [options] [file] ..." print "where command can be:" print " ci|put # checkin the given files" print " co|get # checkout" print " info # print header info" print " head # print revision of head branch" print " list # list filename if valid" print " log # print full log" print " diff # diff rcs file and work file" print "if no files are given, all remote rcs files are assumed" sys.exit(2)
def run(self, args = None): """Process flags, subcommand and options, then run it.""" import getopt, sys if args is None: args = sys.argv[1:] try: opts, args = getopt.getopt(args, self.GlobalFlags) except getopt.error as msg: return self.usage(msg) self.options(opts) if not args: self.ready() return self.default() else: cmd = args[0] mname = 'do_' + cmd fname = 'flags_' + cmd try: method = getattr(self, mname) except AttributeError: return self.usage("command %r unknown" % (cmd,)) try: flags = getattr(self, fname) except AttributeError: flags = '' try: opts, args = getopt.getopt(args[1:], flags) except getopt.error as msg: return self.usage( "subcommand %s: " % cmd + str(msg)) self.ready() return method(opts, args)
def main(my_argv): inputfile = '' output = None if (len(my_argv) <= 3): try: opts, _ = getopt.getopt(my_argv,"i:",["ifile="]) except getopt.GetoptError: print 'Usage: wikistats.py -i <inputfile> [-o <output>]' exit(2) else: try: opts, _ = getopt.getopt(my_argv,"i:o:",["ifile=","output="]) except getopt.GetoptError: print 'Usage: wikistats.py -i <inputfile> [-o <output>]' exit(2) for opt, arg in opts: if opt in ('-h', "--help"): print "wikistats" print print 'Usage: wikistats.py -i <inputfile> [-rev <revision_id>]' print "-i --ifile File to analyze" print "-o --output Type of output. Options: 'json', 'table'. If not specified, JSON is the default." print "-h --help This help." exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-o", "--output"): output = arg return (inputfile,output)
def getopt_parser (ShortOptions, LongOptions): """ Parse command line string using getopt. Return list of files and a dictionary of options! """ args = sys.argv[1:] if len(args)==1 and 'help=' in LongOptions and '--help' in args: options = {'h': None} # print standard help message files = [] elif len(args)>0: try: if LongOptions: OptionsList, files = getopt.getopt(args, ShortOptions, LongOptions) else: OptionsList, files = getopt.getopt(args, ShortOptions) except getopt.error, errMsg: print "\ncheck your options list!!!" print errMsg print "valid options are ", for i in range(len(ShortOptions)): if not ShortOptions[i]==':': print '-' + ShortOptions[i], if LongOptions: for option in LongOptions: print '--' + replace(option,'=',''), raise SystemExit, "parsing input arguments failed!" # return options as a dictionary (getopt returns a double list!) options = {} for i in range(len(OptionsList)): key = replace(OptionsList[i][0],'-','') # remove leading dash(es) options[key] = OptionsList[i][1]
def main(argv): print argv getopt.getopt(argv,"a:m:",["address=", "message="]) try: opts, args = getopt.getopt(argv,"a:m:",["address=", "message="]) except getopt.GetoptError: print 'messenger.py -a address -m message' sys.exit(2) for opt, arg in opts: if opt in ("-a", "--address"): address = arg elif opt in ("-m", "--message"): message = arg print 'Address and Message are: %s, %s.' % (address, message) if address is None or message is None: print 'Both arguments must be defined.' sys.exit(2) fromaddress = '*****@*****.**' # Credentials (if needed) username = '******' password = '******' # The actual mail send server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username,password) server.sendmail(fromaddress, address, message) server.quit()
def main(): global SERVER, PORT, KEY, METHOD, IPv6 logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', filemode='a+') version = '' try: import pkg_resources version = pkg_resources.get_distribution('shadowsocks').version except: pass print 'shadowsocks %s' % version KEY = None METHOD = None IPv6 = False config_path = utils.find_config() optlist, args = getopt.getopt(sys.argv[1:], 'p:k:m:c:6') for key, value in optlist: if key == '-c': config_path = value if config_path: with open(config_path, 'rb') as f: config = json.load(f) logging.info('loading config from %s' % config_path) SERVER = config['server'] PORT = config['server_port'] KEY = config['password'] METHOD = config.get('method', None) optlist, args = getopt.getopt(sys.argv[1:], 'p:k:m:c:6') for key, value in optlist: if key == '-p': PORT = int(value) elif key == '-k': KEY = value elif key == '-m': METHOD = value elif key == '-6': IPv6 = True if not KEY and not config_path: sys.exit('config not specified, please read https://github.com/clowwindy/shadowsocks') encrypt.init_table(KEY, METHOD) if IPv6: ThreadingTCPServer.address_family = socket.AF_INET6 try: server = ThreadingTCPServer(('', PORT), Socks5Server) logging.info("starting server at port %d ..." % PORT) server.serve_forever() except socket.error, e: logging.error(e)
def main(): # Разбираем аргументы командной строки try: opts, args = getopt.getopt(sys.argv[1:], "h", ["help"]) opts, args = getopt.getopt(sys.argv[1:], "g", ["goto"]) except getopt.error, msg: print msg print "для справки используйте --help" sys.exit(2)
def main(args): cmd = args.pop(0) f = globals().get(cmd, cmd_not_found) if hasattr(f, 'lopt'): optlist, args = getopt.getopt(args, f.opt + 'd', f.lopt) else: optlist, args = getopt.getopt(args, f.opt + 'd') optdict = dict(optlist) logging.basicConfig( level=logging.DEBUG if '-d' in optdict else logging.INFO) f(args, optdict)
def parse_args(is_local: bool, version: tuple) -> dict: """parse args from command line and return config dict.""" config_dict = {} if is_local: # is_local is True, local side args_dict, args_left = getopt.getopt(sys.argv[1:], 'hVl:b:s:p:v:', []) for k, v in args_dict: if k == '-h': usage(is_local) sys.exit(0) elif k == '-V': print('DarkChina {}.{}.{}'.format(*version)) sys.exit(0) elif k == '-l': config_dict["local_addr"] = v elif k == '-b': config_dict["local_port"] = int(v) elif k == '-s': config_dict["server_addr"] = v elif k == '-p': config_dict["server_port"] = int(v) elif k == '-v': config_dict["verbose"] = int(v) config_dict.setdefault("local_addr", '127.0.0.1') config_dict.setdefault("local_port", 12306) if not config_dict.get("server_addr", None): print('\nServer address required!') usage(is_local) sys.exit(1) config_dict.setdefault("server_port", 2333) else: # is_local is False, server side args_dict, args_left = getopt.getopt(sys.argv[1:], 'hVs:p:v:', []) for k, v in args_dict: if k == '-h': usage(is_local) sys.exit(0) elif k == '-V': print('DarkChina {}.{}.{}'.format(*version)) sys.exit(0) elif k == '-s': config_dict["server_addr"] = v elif k == '-p': config_dict["server_port"] = int(v) elif k == '-v': config_dict["verbose"] = int(v) config_dict.setdefault("server_addr", '0.0.0.0') config_dict.setdefault("server_port", 2333) # common config config_dict.setdefault("verbose", 2) logging.basicConfig(level=config_dict["verbose"] * 10, format='%(message)s') config_dict.pop("verbose") return config_dict
def main(): import sys import getopt try: opts, args = getopt.getopt(sys.argv[1:], 'h:c:r:t:u:p:a') opts, args = getopt.getopt(sys.argv[1:], 'h:c:r:t') except getopt.GetoptError, e: usage() print '>>>> ERROR: %s' % str(e) sys.exit(2)
def test_from_cmdline(self): import sys rules = ['noarg','witharg='] # if you pass in a garbage option at cmdline getopt will ignore and keep # processing options,remainder = getopt(sys.argv,'',rules) # need to start from sys.argv[1:] with self.assertRaises(GetoptError) as context: options,remainder = getopt(sys.argv[1:],'',rules)
def test_long_outoforder(self): # mixing value and no value args rules = ['noarg','witharg='] expected_result = [('--witharg','foobar'),('--noarg','')] options,remainder = getopt(['--witharg=foobar','--noarg'],'',rules) self.assertListEqual(options, expected_result) expected_result = [('--noarg',''),('--witharg','foobar')] options,remainder = getopt(['--noarg','--witharg=foobar'],'',rules) self.assertListEqual(options, expected_result)
def set_opt(self, o_str = None): optv, wordv = getopt.getopt(sys.argv[1:], self.opt_str, self.long_opt_list) if o_str is not None: optv, wordv = getopt.getopt(o_str.split(), self.opt_str, self.long_opt_list) for o in optv: key, val = o if not self.option.has_key(key): self.option[key] = list() self.option[key].append(val) #print 'db.option: %s: ' % self.option return wordv
def main(argv): if len(argv) < 5 or len(argv) > 8: print("Invalid arguments.") usage() sys.exit(1) format_string = ("i:f:r", "i:f:a:r") try: if "-a" in argv: opts, args = getopt.getopt(sys.argv[1:], format_string[1], ["respectively"]) else: opts, args = getopt.getopt(sys.argv[1:], format_string[0], ["respectively"]) except getopt.GetoptError as err: print(str(err)) sys.exit(2) resflag = False for op, value in opts: if op == "-i": configpath = value elif op == "-f": txtfilepath = value elif op == "-a": attachpath = value elif op in ['-r', '--respectively']: resflag = True else: print(str("Unrecognised option.")) usage() sys.exit(3) # sender = MailSender(smtpserver, useraddr, password) configReader = MailfigReader(configpath, txtfilepath) from_dict = configReader.GetFromDict() smtpserver = from_dict[MailfigReader.KEY_SMTPSV] username = from_dict[MailfigReader.KEY_USRNAME] mailaddr = from_dict[MailfigReader.KEY_USRADDR] password = from_dict[MailfigReader.KEY_USRPWD] sender = MailSender(smtpserver, username, mailaddr, password) to_dict = configReader.GetToDict() fmttext = configReader.GetFmtText() if resflag: sender.SendAllRespective(to_dict, fmttext) else: sender.SendAllOnce(to_dict, fmttext) sys.exit(0)
def parse_args(self, argv): try: if "pacman_server.py" in argv[0]: opts, args = getopt(argv[1:], "p:", ["port="]) else: opts, args = getopt(argv, "p:", ["port="]) except GetoptError: self.usage() for opt, arg in opts: if opt in ("-p", "--port"): self.port = int(arg) else: self.usage()
def parse_args(self, argv): name = directory = argv[0] try: opts, args = getopt.getopt(argv, "d:h", ["dir=", "help"]) for opt, arg in opts: if opt in ("-d", "--dir"): directory = arg elif opt in ("h", "--help"): help() except getopt.GetoptError, e: print e opts, args = getopt.getopt(argv, "", [])
def main(argv): try: opts, args = getopt.getopt(argv, "","") except getopt.GetoptError: print 'Exiting due to error' + GetoptError sys.exit(2) for arg in args: print 'arg: ' + arg print getopt.getopt(argv, '','').keys if __name__ == main: main(sys.argv[1:])
def test_long_multiargs_withvalue(self): rules = ['noarg','noarg2','witharg='] options,remainder = getopt(['--witharg=foobar'],'',rules) self.assertEquals(options[0][0],'--witharg') self.assertEquals(options[0][1],'foobar') # combining novalue and value options,remainder = getopt(['--noarg','--witharg=foobar'],'',rules) for option, value in options: if option == '--witharg': self.assertNotEqual(value,"") else: self.assertEqual(value,"")
def parse_options(): version = '' try: import pkg_resources version = pkg_resources.get_distribution('shadowsocks').version except: pass print 'shadowsocks %s' % version KEY = None METHOD = None IPv6 = False config_path = utils.find_config() try: optlist, args = getopt.getopt(sys.argv[1:], 's:p:k:m:c:6') for key, value in optlist: if key == '-c': config_path = value if config_path: logging.info('loading config from %s' % config_path) try: f = open(config_path, 'rb') config = json.load(f) except ValueError as e: logging.error('found an error in config.json: %s', e.message) sys.exit(1) else: config = {} optlist, args = getopt.getopt(sys.argv[1:], 's:p:k:m:c:6') for key, value in optlist: if key == '-p': config['server_port'] = int(value) elif key == '-k': config['password'] = value elif key == '-s': config['server'] = value elif key == '-m': config['method'] = value elif key == '-6': IPv6 = True except getopt.GetoptError: utils.print_server_help() sys.exit(2) return config
def main(argv): profile_url = '' output_prefix = '' seconds = '20' try: opts, args = getopt.getopt(argv, "h:", ["profile_url=", "output_file_prefix=", "seconds="]) except getopt.GetoptError: print("Incorrect getopt options") print_usage() sys.exit(1) for opt, arg in opts: if opt == '-h': print_usage() sys.exit(1) elif opt in ("--profile_url"): profile_url = arg elif opt in ("--output_file_prefix"): output_file_prefix = arg elif opt in ("--seconds"): seconds = int(arg) else: assert False, "** Unhandled option. **" if ((profile_url == '') or (output_file_prefix == '')): print_usage() sys.exit(1) print("Profile Base URL:" + profile_url) print("Output File Prefix:" + output_file_prefix) heap_prof = YBProf(output_file_prefix, profile_url, seconds) heap_prof.invoke_heap_profile_handler()
def main(argv): """ Parse command line parameters (if any). Command line parameters are expected to take the form: -d : dictionary file -c : spell-checking file Default values are applied where files are not provided. https://docs.python.org/2/library/getopt.html """ # default values - use if not overridden dictionary_file = "testdata/big.txt" check_file = "testdata/yelp100reviews.txt" # read in command line parameters (if any) try: opts, args = getopt.getopt(argv, "d:c:", ["dfile=", "cfile="]) except getopt.GetoptError: print "contextSerial.py -d <dfile> -c <cfile>" print "Default values will be applied." # parse command line parameters for opt, arg in opts: if opt in ("-d", "--dictionary"): dictionary_file = arg elif opt in ("-c", "--cfile"): check_file = arg # return command line parameters (or default values if not provided) return dictionary_file, check_file
def main(argv): inputfile = "main.swift" outputfile = "app.swift" try: opts, args = getopt.getopt(sys.argv[1:], "i:o:", ["inputfile=", "outputfile="]) except getopt.GetoptError as err: handle_error(str(err)) for o, a in opts: if o in ["-i", "--inputfile"]: inputfile = a elif o in ["-o", "--outputfile"]: outputfile = a else: handle_error("unhandled option '{0}' detected".format(o)) # create output file try: f = open(outputfile, "w+") f.close() except IOError: handle_error("failed to write to file, '{0}'.".format(benchmarkfile)) # parse file f = open(outputfile, "w") f.write(includify_file(inputfile))
def Run(argv=None): """standalone command line access point""" if argv is None: argv = sys.argv[1:] from getopt import getopt s_opts = 'hdi' l_opts = ('help', 'duplicates=', 'ignore-comments', 'ignore-imports', 'ignore-docstrings') min_lines = 4 ignore_comments = False ignore_docstrings = False ignore_imports = False opts, args = getopt(argv, s_opts, l_opts) for opt, val in opts: if opt in ('-d', '--duplicates'): min_lines = int(val) elif opt in ('-h', '--help'): usage() elif opt in ('-i', '--ignore-comments'): ignore_comments = True elif opt in ('--ignore-docstrings',): ignore_docstrings = True elif opt in ('--ignore-imports',): ignore_imports = True if not args: usage(1) sim = Similar(min_lines, ignore_comments, ignore_docstrings, ignore_imports) for filename in args: sim.append_stream(filename, open(filename)) sim.run() sys.exit(0)
def main(): try: opts, args = getopt.getopt( sys.argv[1:], 'hqns:', ['help', 'quiet', 'dry-run', 'status=']) except getopt.error, msg: usage(1, msg)
def main(): shortargs = 'vhp:z:o:' longargs = ['verbose', 'help', 'percent=', 'zipfile=', 'outdir='] unzipper = unzip() try: opts, args = getopt.getopt(sys.argv[1:], shortargs, longargs) except getopt.GetoptError: usage() sys.exit(2) zipsource = "" zipdest = "" for o, a in opts: if o in ("-v", "--verbose"): unzipper.verbose = True if o in ("-p", "--percent"): if not unzipper.verbose == True: unzipper.percent = int(a) if o in ("-z", "--zipfile"): zipsource = a if o in ("-o", "--outdir"): zipdest = a if o in ("-h", "--help"): usage() sys.exit() if zipsource == "" or zipdest == "": usage() sys.exit() unzipper.extract(zipsource, zipdest)
def _main(): """\ Usage: tabulate [options] [FILE ...] Pretty-print tabular data. See also https://bitbucket.org/astanin/python-tabulate FILE a filename of the file with tabular data; if "-" or missing, read data from stdin. Options: -h, --help show this message -1, --header use the first row of data as a table header -o FILE, --output FILE print table to FILE (default: stdout) -s REGEXP, --sep REGEXP use a custom column separator (default: whitespace) -F FPFMT, --float FPFMT floating point number format (default: g) -f FMT, --format FMT set output table format; supported formats: plain, simple, grid, fancy_grid, pipe, orgtbl, rst, mediawiki, html, latex, latex_booktabs, tsv (default: simple) """ import getopt import sys import textwrap usage = textwrap.dedent(_main.__doc__) try: opts, args = getopt.getopt(sys.argv[1:], "h1o:s:F:f:", ["help", "header", "output", "sep=", "float=", "format="]) except getopt.GetoptError as e: print(e) print(usage) sys.exit(2) headers = [] floatfmt = "g" tablefmt = "simple" sep = r"\s+" outfile = "-" for opt, value in opts: if opt in ["-1", "--header"]: headers = "firstrow" elif opt in ["-o", "--output"]: outfile = value elif opt in ["-F", "--float"]: floatfmt = value elif opt in ["-f", "--format"]: if value not in tabulate_formats: print("%s is not a supported table format" % value) print(usage) sys.exit(3) tablefmt = value elif opt in ["-s", "--sep"]: sep = value elif opt in ["-h", "--help"]: print(usage) sys.exit(0) files = [sys.stdin] if not args else args with (sys.stdout if outfile == "-" else open(outfile, "w")) as out: for f in files: if f == "-": f = sys.stdin if _is_file(f): _pprint_file(f, headers=headers, tablefmt=tablefmt, sep=sep, floatfmt=floatfmt, file=out) else: with open(f) as fobj: _pprint_file(fobj, headers=headers, tablefmt=tablefmt, sep=sep, floatfmt=floatfmt, file=out)
def main(argv): supported_args = """db= db-user= db-pwd= db-host= db-port= target-schema= analyze-schema= analyze-table= new-dist-key= new-sort-keys= analyze-cols= threads= debug= output-file= do-execute= slot-count= ignore-errors= force= drop-old-data= comprows= query_group= ssl-option= suppress-cloudwatch=""" # extract the command line arguments try: optlist, remaining = getopt.getopt(argv[1:], "", supported_args.split()) except getopt.GetoptError as err: print(str(err)) usage(None) # parse command line arguments args = {} for arg, value in optlist: if arg == "--db": if value == '' or value is None: usage() else: args[config_constants.DB_NAME] = value elif arg == "--db-user": if value == '' or value is None: usage() else: args[config_constants.DB_USER] = value elif arg == "--db-host": if value == '' or value is None: usage() else: args[config_constants.DB_HOST] = value elif arg == "--db-port": if value != '' and value is not None: args[config_constants.DB_PORT] = int(value) elif arg == "--db-pwd": if value != '' and value is not None: args[config_constants.DB_PASSWORD] = value elif arg == "--analyze-schema": if value != '' and value is not None: args[config_constants.SCHEMA_NAME] = value elif arg == "--analyze-table": if value != '' and value is not None: args[config_constants.TABLE_NAME] = value elif arg == "--new-dist-key": if value != '' and value is not None: args['new_dist_key'] = value elif arg == "--new-sort-keys": if value != '' and value is not None: args['new_sort_keys'] = value elif arg == "--analyze-cols": if value != '' and value is not None: args['analyze_col_width'] = value elif arg == "--target-schema": if value != '' and value is not None: args[config_constants.TARGET_SCHEMA] = value elif arg == "--threads": if value != '' and value is not None: args[config_constants.THREADS] = int(value) elif arg == "--debug": if value == 'true' or value == 'True': args[config_constants.DEBUG] = True else: args[config_constants.DEBUG] = False elif arg == "--output-file": sys.stdout = open(value, 'w') elif arg == "--ignore-errors": if value == 'true' or value == 'True': args[config_constants.IGNORE_ERRORS] = True else: args[config_constants.IGNORE_ERRORS] = False elif arg == "--force": if value == 'true' or value == 'True': args[config_constants.FORCE] = True else: args[config_constants.FORCE] = False elif arg == "--drop-old-data": if value == 'true' or value == 'True': args[config_constants.DROP_OLD_DATA] = True else: args[config_constants.DROP_OLD_DATA] = False elif arg == "--do-execute": if value == 'true' or value == 'True': args[config_constants.DO_EXECUTE] = True else: args[config_constants.DO_EXECUTE] = False elif arg == "--slot-count": args[config_constants.QUERY_SLOT_COUNT] = int(value) elif arg == "--comprows": args[config_constants.COMPROWS] = int(value) elif arg == "--query_group": if value != '' and value is not None: args[config_constants.QUERY_GROUP] = value elif arg == "--ssl-option": if value == 'true' or value == 'True': args[config_constants.SSL] = True else: args[config_constants.SSL] = False elif arg == "--suppress-cloudwatch": if value == 'true' or value == 'True': args[config_constants.SUPPRESS_CLOUDWATCH] = True else: args[config_constants.SUPPRESS_CLOUDWATCH] = False else: print("Unsupported Argument " + arg) usage() # Validate that we've got all the args needed if config_constants.DB_NAME not in args: usage("Missing Parameter 'db'") if config_constants.DB_USER not in args: usage("Missing Parameter 'db-user'") if config_constants.DB_HOST not in args: usage("Missing Parameter 'db-host'") if config_constants.DB_PORT not in args: usage("Missing Parameter 'db-port'") if config_constants.SCHEMA_NAME not in args: args[config_constants.SCHEMA_NAME] = 'public' if config_constants.TARGET_SCHEMA not in args: args[config_constants.TARGET_SCHEMA] = args[config_constants.SCHEMA_NAME] # Reduce to 1 thread if we're analyzing a single table if config_constants.TABLE_NAME in args: args[config_constants.THREADS] = 1 # get the database password if config_constants.DB_PASSWORD not in args: args[config_constants.DB_PASSWORD] = getpass.getpass("Password <%s>: " % db_user) # setup the configuration configure(**args) # run the analyser result_code = run() # exit based on the provided return code return result_code
logger.info('Layer dropout: %.5f',config.LAYER_DROPOUT) logger.info('Learning rate: %.5f',config.START_LR) logger.info('='*20) logger.info(config.TF_ANG_VAR_SHAPES_DETACHED) logger.info('=' * 20) logger.info(config.TF_ANG_SCOPES) logger.info('=' * 20) logger.info(config.TF_ANG_STRIDES) logger.info('=' * 20) logger.info('='*40) if __name__ == '__main__': try: opts, args = getopt.getopt( sys.argv[1:], "", ["data-dir="]) except getopt.GetoptError as error: print('<filename>.py --data-dir=<dirname>') print(error) sys.exit(2) if len(opts) != 0: for opt, arg in opts: if opt == '--data-dir': IMG_DIR = str(arg) if IMG_DIR and not os.path.exists(IMG_DIR): os.mkdir(IMG_DIR) if not os.path.exists(IMG_DIR + os.sep + 'random_search'): os.mkdir(IMG_DIR + os.sep + 'random_search')
result.append(cosineSim_docId[1]) #Write the result with the specified format output_file.write(' '.join(map(str, result))) #Prepare new line output_file.write("\n") line = fd.readline() output_file.close fd.close dictionary_file = postings_file = file_of_queries = output_file_of_results = None try: opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:') except getopt.GetoptError: usage() sys.exit(2) for o, a in opts: if o == '-d': dictionary_file = a elif o == '-p': postings_file = a elif o == '-q': file_of_queries = a elif o == '-o': file_of_output = a else: assert False, "unhandled option"
def main(argv): PCAP_IN = None PCAP_OUT = None COMPRESS=False APPEND=False DIFF=False VERBOSE=0 try: opts=getopt.getopt(argv, "hi:o:azdv") for opt, parm in opts[0]: if opt == "-h": usage() raise SystemExit elif opt == "-i": PCAP_IN = parm elif opt == "-o": PCAP_OUT = parm elif opt == "-v": VERBOSE += 1 elif opt == "-d": DIFF = True elif opt == "-a": APPEND = True elif opt == "-z": COMPRESS = True if PCAP_IN is None: raise getopt.GetoptError("Missing pcap file (-i)") except getopt.GetoptError as e: print("ERROR: %s" % e, file = sys.stderr) raise SystemExit from scapy3k.config import conf from scapy3k.utils import RawPcapReader,RawPcapWriter,hexdiff from scapy3k.layers import all pcap = RawPcapReader(PCAP_IN) pcap_out = None if PCAP_OUT: pcap_out = RawPcapWriter(PCAP_OUT, append=APPEND, gz=COMPRESS, linktype=pcap.linktype) pcap_out._write_header(None) LLcls = conf.l2types.get(pcap.linktype) if LLcls is None: print(" Unknown link type [%i]. Can't test anything!" % pcap.linktype, file = sys.stderr) raise SystemExit i=-1 differ=0 failed=0 for p1,meta in pcap: i += 1 try: p2d = LLcls(p1) p2 = str(p2d) except KeyboardInterrupt: raise except Exception as e: print("Dissection error on packet %i" % i) failed += 1 else: if p1 == p2: if VERBOSE >= 2: print("Packet %i ok" % i) continue else: print("Packet %i differs" % i) differ += 1 if VERBOSE >= 1: print(repr(p2d)) if DIFF: hexdiff(p1,p2) if pcap_out is not None: pcap_out.write(p1) i+=1 correct = i-differ-failed print("%i total packets. %i ok, %i differed, %i failed. %.2f%% correct." % (i, correct, differ, failed, i and 100.0*(correct)/i))
def main(): host = "localhost" port = 4433 num_limit = None run_exclude = set() argv = sys.argv[1:] opts, args = getopt.getopt(argv, "h:p:e:n:", ["help"]) for opt, arg in opts: if opt == '-h': host = arg elif opt == '-p': port = int(arg) elif opt == '-e': run_exclude.add(arg) elif opt == '-n': num_limit = int(arg) elif opt == '--help': help_msg() sys.exit(0) else: raise ValueError("Unknown option: {0}".format(opt)) if args: run_only = set(args) else: run_only = None conversations = {} conversation = Connect(host, port) node = conversation ciphers = [ CipherSuite.TLS_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV ] ext = {} groups = [GroupName.secp256r1] ext[ExtensionType.key_share] = key_share_ext_gen(groups) ext[ExtensionType.supported_groups] = SupportedGroupsExtension()\ .create(groups) sig_algs = [ SignatureScheme.rsa_pss_rsae_sha256, SignatureScheme.rsa_pss_pss_sha256, SignatureScheme.rsa_pkcs1_sha256 ] ext[ExtensionType.signature_algorithms] = SignatureAlgorithmsExtension()\ .create(sig_algs) ext[ExtensionType.signature_algorithms_cert] = \ SignatureAlgorithmsCertExtension().create(RSA_SIG_ALL) node = node.add_child(ClientHelloGenerator(ciphers, extensions=ext)) ext = {ExtensionType.renegotiation_info: None} node = node.add_child(ExpectServerHello(version=(3, 3), extensions=ext)) node = node.add_child(ExpectCertificate()) node = node.add_child(ExpectServerKeyExchange()) node = node.add_child(ExpectServerHelloDone()) node = node.add_child(ClientKeyExchangeGenerator()) node = node.add_child(ChangeCipherSpecGenerator()) node = node.add_child(FinishedGenerator()) node = node.add_child(ExpectChangeCipherSpec()) node = node.add_child(ExpectFinished()) node = node.add_child( ApplicationDataGenerator(bytearray(b"GET / HTTP/1.0\n\n"))) node = node.add_child(ExpectApplicationData()) node = node.add_child( AlertGenerator(AlertLevel.warning, AlertDescription.close_notify)) node = node.add_child(ExpectAlert()) node.next_sibling = ExpectClose() conversations["sanity"] = conversation for tls_ver in range(50): conversation = Connect(host, port) node = conversation ciphers = [ CipherSuite.TLS_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV ] ext = {} groups = [GroupName.secp256r1] ext[ExtensionType.key_share] = key_share_ext_gen(groups) # draft versions of TLS 1.3 used major version of 127 and minor version # equal to the draft version (e.g. draft-23 used (127, 23)) ext[ExtensionType.supported_versions] = SupportedVersionsExtension()\ .create([(127, tls_ver), (3, 3)]) ext[ExtensionType.supported_groups] = SupportedGroupsExtension()\ .create(groups) sig_algs = [ SignatureScheme.rsa_pss_rsae_sha256, SignatureScheme.rsa_pss_pss_sha256, SignatureScheme.rsa_pkcs1_sha256 ] ext[ExtensionType.signature_algorithms] = SignatureAlgorithmsExtension()\ .create(sig_algs) ext[ExtensionType.signature_algorithms_cert] = \ SignatureAlgorithmsCertExtension().create(RSA_SIG_ALL) node = node.add_child(ClientHelloGenerator(ciphers, extensions=ext)) # version in TLS 1.3 enabled tlsfuzzer actually does check the # supported versions extension node = node.add_child(ExpectServerHello(version=(3, 3))) node = node.add_child(ExpectCertificate()) node = node.add_child(ExpectServerKeyExchange()) node = node.add_child(ExpectServerHelloDone()) node = node.add_child(ClientKeyExchangeGenerator()) node = node.add_child(ChangeCipherSpecGenerator()) node = node.add_child(FinishedGenerator()) node = node.add_child(ExpectChangeCipherSpec()) node = node.add_child(ExpectFinished()) node = node.add_child( ApplicationDataGenerator(bytearray(b"GET / HTTP/1.0\r\n\r\n"))) node = node.add_child(ExpectApplicationData()) node = node.add_child( AlertGenerator(AlertLevel.warning, AlertDescription.close_notify)) node = node.add_child(ExpectAlert()) conversations["try negotiating (127, {0}) - draft version" .format(tls_ver)] = \ conversation conversation = Connect(host, port) node = conversation ciphers = [ CipherSuite.TLS_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV ] ext = {} groups = [GroupName.secp256r1] ext[ExtensionType.key_share] = key_share_ext_gen(groups) ext[ExtensionType.supported_versions] = SupportedVersionsExtension()\ .create([(3, 4), (3, 3)]) ext[ExtensionType.supported_groups] = SupportedGroupsExtension()\ .create(groups) sig_algs = [ SignatureScheme.rsa_pss_rsae_sha256, SignatureScheme.rsa_pss_pss_sha256, SignatureScheme.rsa_pkcs1_sha256 ] ext[ExtensionType.signature_algorithms] = SignatureAlgorithmsExtension()\ .create(sig_algs) ext[ExtensionType.signature_algorithms_cert] = \ SignatureAlgorithmsCertExtension().create(RSA_SIG_ALL) node = node.add_child(ClientHelloGenerator(ciphers, extensions=ext)) # version in TLS 1.3 enabled tlsfuzzer actually does check the # supported versions extension node = node.add_child(ExpectServerHello(version=(3, 3))) node = node.add_child(ExpectCertificate()) node = node.add_child(ExpectServerKeyExchange()) node = node.add_child(ExpectServerHelloDone()) node = node.add_child(ClientKeyExchangeGenerator()) node = node.add_child(ChangeCipherSpecGenerator()) node = node.add_child(FinishedGenerator()) node = node.add_child(ExpectChangeCipherSpec()) node = node.add_child(ExpectFinished()) node = node.add_child( ApplicationDataGenerator(bytearray(b"GET / HTTP/1.0\r\n\r\n"))) node = node.add_child(ExpectApplicationData()) node = node.add_child( AlertGenerator(AlertLevel.warning, AlertDescription.close_notify)) node = node.add_child(ExpectAlert()) conversations["try negotiating TLS 1.3"] = \ conversation # run the conversation good = 0 bad = 0 failed = [] if not num_limit: num_limit = len(conversations) # make sure that sanity test is run first and last # to verify that server was running and kept running throughout sanity_tests = [('sanity', conversations['sanity'])] regular_tests = [(k, v) for k, v in conversations.items() if k != 'sanity'] sampled_tests = sample(regular_tests, min(num_limit, len(regular_tests))) ordered_tests = chain(sanity_tests, sampled_tests, sanity_tests) for c_name, c_test in ordered_tests: if run_only and c_name not in run_only or c_name in run_exclude: continue print("{0} ...".format(c_name)) runner = Runner(c_test) res = True try: runner.run() except Exception: print("Error while processing") print(traceback.format_exc()) res = False if res: good += 1 print("OK\n") else: bad += 1 failed.append(c_name) print("Test to verify that TLS 1.3 is disabled/not-supported in server") print("Also attempts connections using draft versions of the protocol.") print("version: {0}\n".format(version)) print("Test end") print("successful: {0}".format(good)) print("failed: {0}".format(bad)) failed_sorted = sorted(failed, key=natural_sort_keys) print(" {0}".format('\n '.join(repr(i) for i in failed_sorted))) if bad > 0: sys.exit(1)
def main(): config = {"addr": "127.0.0.1", "port": "7227", "language": "en"} try: config['language'] = os.environ['LANG'][0:2] except Exception: pass if (not exists(join(pypath, "locale", config['language']))) or config['language'] == "": config['language'] = "en" configFile = ConfigParser.ConfigParser() configFile.read(join(homedir, ".pyload-cli")) if configFile.has_section("cli"): for opt in configFile.items("cli"): config[opt[0]] = opt[1] gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None]) translation = gettext.translation("Cli", join(pypath, "locale"), languages=[config['language'], "en"], fallback=True) translation.install(unicode=True) interactive = False command = None username = "" password = "" shortOptions = 'iu:p:a:hcl:' longOptions = ['interactive', "username="******"pw=", "address=", "port=", "help", "commands", "language="] try: opts, extraparams = getopt(sys.argv[1:], shortOptions, longOptions) for option, params in opts: if option in ("-i", "--interactive"): interactive = True elif option in ("-u", "--username"): username = params elif option in ("-a", "--address"): config['addr'] = params elif option in ("-p", "--port"): config['port'] = params elif option in ("-l", "--language"): config['language'] = params gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None]) translation = gettext.translation("Cli", join(pypath, "locale"), languages=[config['language'], "en"], fallback=True) translation.install(unicode=True) elif option in ("-h", "--help"): print_help(config) exit() elif option in ("--pw"): password = params elif option in ("-c", "--comands"): print_commands() exit() except GetoptError: print 'Unknown Argument(s) "%s"' % " ".join(sys.argv[1:]) print_help(config) exit() if len(extraparams) >= 1: command = extraparams client = False if interactive: try: client = ThriftClient(config['addr'], int(config['port']), username, password) except WrongLogin: pass except NoSSL: print _("You need py-openssl to connect to this pyLoad Core.") exit() except NoConnection: config['addr'] = False config['port'] = False if not client: if not config['addr']: config['addr'] = raw_input(_("Address: ")) if not config['port']: config['port'] = raw_input(_("Port: ")) if not username: username = raw_input(_("Username: "******"Password: "******"Login data is wrong.") except NoConnection: print _("Could not establish connection to %(addr)s:%(port)s." % {"addr": config['addr'], "port": config['port']}) else: try: client = ThriftClient(config['addr'], int(config['port']), username, password) except WrongLogin: print _("Login data is wrong.") except NoConnection: print _("Could not establish connection to %(addr)s:%(port)s." % {"addr": config['addr'], "port": config['port']}) except NoSSL: print _("You need py-openssl to connect to this pyLoad core.") if interactive and command: print _("Interactive mode ignored since you passed some commands.") if client: writeConfig(config) cli = Cli(client, command)
import json from os import path import glob from datetime import datetime as datelib import numpy as np import re import matplotlib.pyplot as plt import sys import getopt import csv argv = sys.argv[1:] type = '' try: opts, args = getopt.getopt(argv, "ht:") except getopt.GetoptError: print 'upsat-plotter.py -t <EXT_WOD>/<WOD> <parameters>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'upsat-plotter.py -t [EXT_WOD/WOD] <parameters>' sys.exit() elif opt in ("-t"): type = arg arg_in = sys.argv[3:] # If EX_WOD different from WOD if type == "EXT_WOD": dir_path = path.relpath("EXT_WOD_RX") file_list = glob.glob(dir_path + "/*.json")
def main(argv): try: gopts, args = getopt.getopt(argv[1:], "vi:") except getopt.GetoptError: print "Usage: %s [-v] [-i ignorepath]* [path]" % argv[0] return 2 opts = {} for opt, val in gopts: if opt == '-i': val = abspath(val) opts.setdefault(opt, []).append(val) if len(args) == 0: path = '.' elif len(args) == 1: path = args[0] else: print "Usage: %s [-v] [-i ignorepath]* [path]" % argv[0] return 2 verbose = '-v' in opts num = 0 out = cStringIO.StringIO() # TODO: replace os.walk run with iteration over output of # `svn list -R`. for root, dirs, files in os.walk(path): if '.svn' in dirs: dirs.remove('.svn') if '-i' in opts and abspath(root) in opts['-i']: del dirs[:] continue # XXX: awkward: for the Makefile call: don't check non-package # files for file headers in_pocoo_pkg = root.startswith('./pygments') for fn in files: fn = join(root, fn) if fn[:2] == './': fn = fn[2:] if '-i' in opts and abspath(fn) in opts['-i']: continue ext = splitext(fn)[1] checkerlist = checkers.get(ext, None) if not checkerlist: continue if verbose: print "Checking %s..." % fn try: f = open(fn, 'r') lines = list(f) except (IOError, OSError), err: print "%s: cannot open: %s" % (fn, err) num += 1 continue for checker in checkerlist: if not in_pocoo_pkg and checker.only_pkg: continue for lno, msg in checker(fn, lines): print >>out, "%s:%d: %s" % (fn, lno, msg) num += 1
def grabargs(): # "Grab command-line arguments" options ={ "fname": '', "suggestion" : False, "ignore" : False, "limit" : False, "compare" : False, "disableSyntax" : False, "disableSemantic" : False, "disableStatistic" : False, "strip_tashkeel" : False, "reducedTashkeel" : False, "progress" : False, "train" : False, "nocache" : False, "text" : "", } if not sys.argv[1:]: usage() sys.exit(0) try: opts, args = getopt.getopt(sys.argv[1:], "hVtgcpixsmnrv:f:l:", ["help", "version", "stat", "compare", "reduced", "strip", "syntax", "progress", "semantic", "ignore", "nocache", "train", "limit=", "file="], ) except getopt.GetoptError: usage() sys.exit(0) for o, val in opts: if o in ("-h", "--help"): usage() sys.exit(0) if o in ("-V", "--version"): print scriptversion sys.exit(0) if o in ("-x", "--syntax"): options["disableSyntax"] = True if o in ("-s", "--strip"): options["strip_tashkeel"] = True if o in ("-r", "--reduced"): options["reducedTashkeel"] = True if o in ("-m", "--semantic"): options["disableSemantic"] = True if o in ("-i", "--ignore"): options["ignore"] = True if o in ("-n", "--nocache"): options["nocache"] = True if o in ("-c", "--compare"): options["compare"] = True if o in ("-t", "--stat"): options["disableStatistic"] = True if o in ("-p", "--progress"): options["progress"] = True if o in ("-g", "--train"): options["train"] = True if o in ("-l", "--limit"): try: options["limit"] = int(val) except: options["limit"] = 0 if o in ("-f", "--file"): options["fname"] = val utfargs = [] for a in args: utfargs.append( a.decode('utf8')) options["text"] = u' '.join(utfargs) #if text: print text.encode('utf8') return (options)
sh_cmd = '/bin/sh -f' sh_ext = 'sh' python_lang = 'python' python_cmd = '/usr/bin/python' python_ext = 'py' # curl_cmd must be generic for cross platform support curl_cmd = 'curl' dest_dir = '.' # Only run interactive commands if called directly as executable if __name__ == '__main__': opts_str = 'c:d:hp:s:tvV' try: (opts, args) = getopt.getopt(sys.argv[1:], opts_str) except getopt.GetoptError, goe: print 'Error: %s' % goe usage() sys.exit(1) for (opt, val) in opts: if opt == '-c': curl_cmd = val elif opt == '-d': dest_dir = val elif opt == '-i': include_license = False elif opt == '-p': python_cmd = val elif opt == '-s':
# import sys import json import email import pyzor.digest #---------------------------------------------------------------------- import getopt def usage(): return "Prints a message’s digest payload in newline-delimited JSON.\n\n" + "Usage: " + sys.argv[0] + "\n\nGive input via STDIN.\n"; try: (opts, args) = getopt.getopt(sys.argv[1:], 'h', ['help']) except getopt.GetoptError, err: sys.stderr.write(usage()) sys.exit(1) for (o, a) in opts: if o in ('-h', '--help'): print usage() sys.exit(); #---------------------------------------------------------------------- msg = email.message_from_file( sys.stdin ) import pprint digester=pyzor.digest.DataDigester
outlen = int(line.split("Outputlen = ")[1])//8 print(line) elif line.startswith("Output = "): output = hash.hash(msg, length=outlen) print("Output =", "".join(("%02x" % x for x in output))) elif line.startswith("MD = "): output = hash.hash(msg, length=outlen) print("MD =", "".join(("%02x" % x for x in output))) if __name__ == '__main__': def usage(err=1): print("usage: TODO", file=sys.stderr) exit(err) opts,args = getopt.getopt(sys.argv[1:], "", ["test=","hash=","seed=","min-len=","max-len=","file="]) if len(args) != 0 or len(opts) != len(set(opts)): usage() opts = dict(opts) hashes = { "SHA3_224":Strobe.Keccak.SHA3_224, "SHA3_256":Strobe.Keccak.SHA3_256, "SHA3_384":Strobe.Keccak.SHA3_384, "SHA3_512":Strobe.Keccak.SHA3_512, "SHAKE128":Strobe.Keccak.SHAKE128, "SHAKE256":Strobe.Keccak.SHAKE256 } if "--hash" in opts and opts["--hash"] in hashes: hash = hashes[opts["--hash"]] else: usage()
def main(argv): #Set default variable values verbose = False disallowed = '' config_file = 'santa.yaml' santas_list = [] send = False usage = ' $santa.py -i <config_file.yaml> --send --verbose' #CLI Inputs try: opts, args = getopt.getopt(argv,"hivs",["ifile=","send", "verbose"]) except getopt.GetoptError: print(usage) sys.exit(2) for opt, arg in opts: if opt == '-h': print(usage) sys.exit() elif opt in ("-v", "--verbose"): verbose = True elif opt in ("-s", "--send"): send = True elif opt in ("-i", "--ifile"): config_file = arg if verbose == True: print('Running against {}, with verbosity of {} and send as {}.'.format(config_file, str(send), str(verbose))) #Herein lies the bulk of the main method try: #Import config data participant_data = get_config(config_file, verbose) participant_list = participant_data['participant_data'] blacklist = participant_data['blacklist'] email_data = participant_data['email'] price_limit = participant_data['price_limit'] #populate people objects, creating 'Santa's List' for name, email in participant_list.items(): name = initialise_person(name, email , blacklist, verbose) santas_list.append(name) if verbose == True: print('[I]Santas List is:') for p in santas_list: print(' -{}'.format(p.name)) #Sort participants by blacklist associated first santas_list.sort(key=lambda x: x.ban_count, reverse=True) #sort by banned match count if verbose == True: print('[I]Santas list has been optimised to:') for p in santas_list: print(' -{}'.format(p.name)) #loop through list and match for person in santas_list: matched = get_match(person, santas_list, verbose) if matched == False: raise ValueError('[X]Unable to find a match for {}, check your blacklist is not restrictive.'.format(person.name)) #Matchin complete if verbose == True: print("""[!]Matches are:""") for person in santas_list: print(' [M]{} - {}'.format(person.name, person.match)) if send == False: print("""[!]Pairing Complete!\nYou can send these pairings out by calling the script with the send options.\n\n {}\n\nHave a nice day!""".format(usage)) else: if verbose == True: print('[!]Sending emails.') for person in santas_list: print("Sending email to {}.".format(person.name)) send_email(person, email_data, price_limit) except: fatal="""[!]Fatal Error matching your users, perhaps the blacklist is prohibitive,or the list too short. Try re-structuring these, adding more users, or removing disallowed matches altogether. If you still cannot get successful matchin, try running in verbose mode""" print('\033[91m' + fatal + '\033[0m') e = sys.exc_info()[0] print('\n\nException Detail:\n {}'.format(e)) print(sys.exc_info())
def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help', 'directory=']) except getopt.error, msg: usage(1, msg)
'dqn.replay_memory_size': 500000, 'dqn.no_replay': False, 'dqn.network': network.build_nature, 'dqn.updates': lasagne.updates.rmsprop } if __name__ == "__main__": import sys import getopt optlist, args = getopt.getopt(sys.argv[1:], '', [ 'visualize=', 'record_dir=', 'dqn.replay_start_size=', 'dqn.final_epsilon=', 'dqn.initial_epsilon=', 'dqn.log_frequency=', 'replay_memory_size=', 'theano_verbose=', 'weights_dir=', 'show_mood=', 'dqn.no_replay', 'dqn.network=', 'dqn.updates=']) for o, a in optlist: if o in ("--visualize",): d['visualize'] = a elif o in ("--record_dir",): d['record_dir'] = a elif o in ("--weights_dir",): d['weights_dir'] = a elif o in ("--dqn.replay_start_size",):
def _handleopts(): for opt in argv[1:]: if opt in ("-h", "--help"): print "%s" % (__usage__), raise SystemExit if opt in ("-v", "--version"): print "%s (%s)" % (__version__, __lastedit__), raise SystemExit _method_ = 'ifconfig_suid.cgi' _file_ = 'ifconfig.cgi' for opt in argv[1:]: if opt == "-1": _method_ = 'ifconfig_suid.cgi' elif opt == "-2": _method_ = 'reboot_suid.cgi' _file_ = 'reboot.cgi' elif opt == "-3": _method_ = 'proxy_suid.cgi' _file_ = 'proxy.cgi' elif opt == "-4": _method_ = 'edittmpl_suid.cgi' _file_ = 'edittmpl.cgi' elif opt == "-5": _method_ = 'version_suid.cgi' _file_ = 'version.cgi' elif opt == "-6": _method_ = 'hostname_suid.cgi' _file_ = 'hostname.cgi' elif opt == "-7": _method_ = 'gateway_suid.cgi' _file_ = 'gateway.cgi' elif opt == "-8": _method_ = 'halt_suid.cgi' _file_ = 'halt.cgi' elif opt == "-9": _method_ = 'edituserdb_suid.cgi' _file_ = 'edituserdb.cgi' elif opt == "-10": _method_ = 'htpasswd_suid.cgi' _file_ = 'htpasswd.cgi' elif opt == "-11": _method_ = 'pattern_up_suid.cgi' _file_ = 'pattern_up.cgi' elif opt == "-12": _method_ = 'license_suid.cgi' _file_ = 'license.cgi' elif opt == "-13": _method_ = 'iptables_suid.cgi' _file_ = 'iptables.cgi' elif opt == "-14": _method_ = 'dns_suid.cgi' _file_ = 'dns.cgi' elif opt == "-15": _method_ = 'pattern_autoup_suid.cgi' _file_ = 'pattern_autoup.cgi' elif opt == "-16": _method_ = 'spam_list_suid.cgi' _file_ = 'spam_list.cgi' elif opt == "-17": _method_ = 'diag_suid.cgi' _file_ = 'diag.cgi' else: pass try: opts = getopt.getopt(argv[1:], 'c1234567890s:d:', ['clean', \ 'suid=', \ 'dir='])[0] except Exception, (err): print "[-] %s" % (err), raise SystemExit
y_test = [e.split('#') for e in y_test] for klass_name in names_list: with open(os.path.join(pascalvoc_path, 'ImageSets', 'Main', f'{klass_name}_train.txt'), 'w') as filehandle: for filename, klasses in zip(X_train, y_train): flag = ' 1' if klass_name in klasses else '-1' filehandle.writelines(f"{filename} {flag}\n") with open(os.path.join(pascalvoc_path, 'ImageSets', 'Main', f'{klass_name}_val.txt'), 'w') as filehandle: for filename, klasses in zip(X_test, y_test): flag = ' 1' if klass_name in klasses else '-1' filehandle.writelines(f"{filename} {flag}\n") if __name__ == '__main__': command_help = 'pascalvoc_split.py --pascalvoc_path <pascalvocpath> --test_size <float>' argv = sys.argv[1:] try: opts, args = getopt.getopt(argv, 'h', ['=', 'pascalvoc_path=', 'test_size=']) except getopt.GetoptError: print(command_help) sys.exit(2) pascalvoc_path, test_size = [None, None] for opt, arg in opts: if opt == '-h': print(command_help) sys.exit() elif opt in ("--pascalvoc_path"): pascalvoc_path = arg elif opt in ("--test_size"): test_size = float(arg) if None in [pascalvoc_path, test_size]: print(command_help) sys.exit()
print("Usage: %s [-e /path/to/exclude_file] [-E] [-u <username>] [-p <password>] [-n] [-D] [-v]" % sys.argv[0]) print("") print("-e /path/to/exclude_file => Allows user to define a Python List of Patches NOT to install.") print("-E => *Disable* the loading of auto-exclusions list from Github") print("-n => Check for available patches and return Nagios OK or WARN for system monitoring") print("-u <username> => xe username - for nagios monitoring") print("-p <passwd> => xe password - for nagios monitoring") print("-D => Enable DEBUG output") print("-v => Display Version and Exit.") print("-h => Display this message and Exit.") sys.exit(exval) # Parse Args: try: myopts, args = getopt.getopt(sys.argv[1:],"vhe:Eu:p:nrD") except getopt.GetoptError: usage() for o, a in myopts: if o == '-v': # Version print and Quit. print("Citrix_XenServer_Patch_Checker_Version: " + str(version)) sys.exit(0) if o == '-h': # Version print and Quit. usage(0) elif o == '-e': # Set the exclusion file exclude_file = str(a) # Check the file exists
def main(argv): import getopt import fileinput def usage(): print 'usage: %s [-v] [-o out.wav] [script ...]' % argv[0] return 100 def getv(v): try: if '.' in v: return float(v) else: return int(v) except ValueError: return 0 try: (opts, args) = getopt.getopt(argv[1:], 'vo:') except getopt.GetoptError: return usage() verbose = 0 outfp = None for (k, v) in opts: if k == '-v': verbose += 1 elif k == '-o': outfp = open(v, 'wb') # if not args: return usage() path = args.pop(0) src = WaveReader(path) # waves = [] for line in fileinput.input(args): (line, _, _) = line.partition('#') line = line.strip() if not line: continue (t, dur, path) = line.split('\t') t = getv(t) dur = getv(dur) wav = WaveReader(path) assert wav.nchannels == src.nchannels assert wav.sampwidth == src.sampwidth #assert wav.framerate == src.framerate if isinstance(t, float): t = int(t * src.framerate) if isinstance(dur, float): dur = int(dur * src.framerate) buf = wav.read(dur) wav.close() waves.append((t, buf)) waves.append((src.nframes, [])) # if outfp is not None: dst = WaveWriter(outfp, nchannels=src.nchannels, sampwidth=src.sampwidth, framerate=src.framerate) else: dst = WavePlayer(nchannels=src.nchannels, sampwidth=src.sampwidth, framerate=src.framerate) # t0 = 0 bufs = [] for (t1, buf1) in sorted(waves, key=lambda (t, _): t): dt = (t1 - t0) * dst.nchannels tmp = [src.read(t1 - t0)] assert len(tmp[0]) == dt for (i, b) in enumerate(bufs): if dt <= len(b): tmp.append(b[:dt]) else: tmp.append(b + [0] * (dt - len(b))) bufs[i] = b[dt:] bufs.append(buf1) bufs = [b for b in bufs if b] dst.write(mix(tmp)) t0 = t1 # dst.close() if outfp is not None: outfp.close() return
WP_WIDTH = 128 FL_PENALTY = 0.5 FN_PENALTY = 1.2 WL_PENALTY = 1 LEARNING_RATE = 0.01 W2V_MIN_COUNT = 1 W2V_SIZE = 200 W2V_WINDOW = 5 ITERATION_COUNT = 1 TRAIN_DIR = "./Data/Train/" TEST_DIR = "./Data/Test/" CKPT_PATH = "./Checkpoints/local.ckpt" RESTORE = False SAVE = False opts, args = getopt.getopt(sys.argv[1:],"n:l:d:rs:",[]) for opt, arg in opts: if opt == '-n': ITERATION_COUNT = int(arg) elif opt == '-l': LEARNING_RATE = float(arg) elif opt == '-d': TRAIN_DIR = arg + "/Train" TEST_DIR = arg + "/Test" elif opt == '-r': RESTORE = True elif opt == '-s': SAVE = True CKPT_PATH = arg train_wordfiles = filter(lambda filename: filename.endswith('wordsList.txt') , listdir(TRAIN_DIR))
cmsis_svd.model.SVDRegister.__lt__ = sort_by_address_offset cmsis_svd.model.SVDField.__lt__ = sort_by_bit_offset def usage(msg=None): if (msg != None): print(msg) print("""usage: %s [-d device or -s file.svd] [options] -d: svd device file to load -w: write output -l: list cmsis_svd devices'""" % sys.argv[0]) exit(1) try: opts, args = getopt.getopt(sys.argv[1:], "ld:cp:w", ["list", "device", "no_comment", "peripheral"]) except getopt.GetoptError as err: print(str(err)) usage() sys.exit(2) do_list = False selected_device = None selected_peripheral = None svd_file = None no_comments = True no_doxygen = False output = None verbose = False for o, a in opts:
def main(argv): ## ============ Determine input argumentts =============== ## # Default values filename_img = 'QSM.nii.gz' filename_roi = 'label.nii.gz' filename_out = 'stats.csv' verbose = False try: opts, args = getopt.getopt(argv,"hi:r:o:v",[]) except getopt.GetoptError: print('calc_roi.py -i <filename_img> -r <filename_roi> -o <filename_out> \ [-v | verbose]') sys.exit(2) for opt, arg in opts: if opt == '-h': print('calc_roi.py -i <filename_img> -r <filename_roi> -o <filename_out>') sys.exit() elif opt == '-i': filename_img = arg elif opt == '-r': filename_roi = arg elif opt == '-o': filename_out = arg elif opt == '-v': verbose = True ## =================== Parameter setting ===================== ## num_classes = 11 # 10 DGM + 1 Background labels = ['Red Nucleus (L)', 'Red Nucleus (R)', 'Substantia Nigra (L)', 'Substantia Nigra (R)', 'Globus Pallidus (L)', 'Globus Pallidus (R)', 'Putamen (L)', 'Putamen (R)', 'Caudate Nucleus (L)', 'Caudate Nucleus (R)'] labels_abbr = ['RN(L)', 'RN(R)', 'SN(L)', 'SN(R)', 'GP(L)', 'GP(R)', 'PU(L)', 'PU(R)', 'CN(L)', 'CN(R)'] ## ==================== Load QSM (nifti) ===================== ## img = nib.load(filename_img) matrix_size = img.shape voxel_size = img.header.get_zooms() QSM = img.get_data().astype(precision_global) # remove background QSM[QSM < -10000] = 0.0 ## ==================== Load ROI (nifti) ===================== ## roi = nib.load(filename_roi) assert matrix_size == roi.shape, 'Matrix size should match for image and ROI' ROI = roi.get_data().astype(np.int) ## ======================= Measure ROI ======================= ## df = pd.DataFrame(index=labels_abbr, columns=['Mean', 'Std']) for i, label in zip(np.arange(2, 2+num_classes-1), labels_abbr): df.loc[label, 'Mean'] = np.mean(QSM[ROI == i]) df.loc[label, 'Std'] = np.std(QSM[ROI == i]) if verbose: print(df) ## ======================= Save stats ======================== ## df.to_csv(filename_out) sys.exit(0)
def main(argv): global l global baseUrl initLogger() l.info("mpulse-annotator is starting...") # Read and parse the command line arguments baseUrl = '' # -u command line argument clientToken = '' # -c command line argument clientSecret = '' # -s command line argument accessToken = '' # -o command line argument fromtime = '' # -t command line argument apitoken = '' # -a command line argument mpulsetenant = '' # -m command line argument eventsSelectorFile = None # -f command line argument simulateAdd = False # -x command line argument try: opts, args = getopt.getopt(argv, "hu:c:s:o:t:a:m:f:x", [ "baseurl", "clienttoken", "clientsecret", "accesstoken", "fromtime=", "apitoken", "mpulsetenant", "eventsselector", "simulate" ]) except getopt.GetoptError: print( 'mpulse-annotator.py -u <baseurl> -c <clienttoken> -s <clientsecret> -o <accesstoken> -t <fromtime> -a <apitoken> -m <mpulsetenant> -f <events-selector-file>' ) sys.exit(2) for opt, arg in opts: if opt == '-h': print( 'mpulse-annotator.py -u <baseurl> -c <clienttoken> -s <clientsecret> -o <accesstoken> -t <fromtime> -a <apitoken> -m <mpulsetenant> -f <events-selector-file>' ) sys.exit() elif opt in ("-u", "--baseurl"): baseUrl = 'https://%s' % arg elif opt in ("-c", "--clienttoken"): clientToken = arg elif opt in ("-s", "--clientsecret"): clientSecret = arg elif opt in ("-o", "--accesstoken"): accessToken = arg elif opt in ("-t", "--fromtime"): fromtime = arg l.info('events will be filtered starting from ' + fromtime) elif opt in ("-a", "--apitoken"): apitoken = arg l.info("using mPulse API token: " + apitoken) elif opt in ("-m", "--mpulsetenant"): mpulsetenant = arg l.info("using mPulse tenant: " + mpulsetenant) elif opt in ("-f", "--eventsselector"): eventsSelectorFile = arg l.info("using events selector file: " + eventsSelectorFile) elif opt in ("-x"): simulateAdd = True # Get a mPulse API handler and retrieve a security token valid for this session if simulateAdd: l.info( '[SIMULATE] Important: No annotation will be added to mPulse dashboard (simulation mode)' ) mpulse = MPulseAPIHandler(l, simulateAdd) mpulsetoken = mpulse.getSecurityToken(apitoken, mpulsetenant) # Create a dictionary to select events during parsing of API call responses if eventsSelectorFile is None: eventsSelectorFile = EVENTS_SELECTOR_FILE l.info('loading events selector from file ' + eventsSelectorFile) eventsSelector = parseEventsSelector(EVENTS_SELECTOR_FILE) sess = requests.Session() l.info("session created on " + baseUrl + ", using client token '" + clientToken + "' and start time '" + fromtime + "'") #sess.auth = EdgeGridAuth.from_edgerc(edgerc, edgercSection) sess.auth = EdgeGridAuth(client_token=clientToken, client_secret=clientSecret, access_token=accessToken) events = [] events = getEventViewerEvents(sess, fromtime, eventsSelector) for e in events: l.info('The following annotation will be sent to mPulse API:') l.info(' Title: ' + e.getAnnotationTitle()) l.info(' Text: ' + e.getAnnotationText()) l.info(' Start: ' + e.getEventStartTime()) mpulse.addAnnotation(mpulsetoken, e.getAnnotationTitle(), e.getAnnotationText(), e.getEventStartTime()) l.info('Pause ' + str(ANNOTATION_CREATE_DELAY) + ' seconds...') time.sleep(ANNOTATION_CREATE_DELAY) date_time_obj = datetime.datetime.strptime(fromtime + '.000+0000', '%Y-%m-%dT%H:%M:%S.%f%z') fromtimeTS = str(int(date_time_obj.timestamp())) events = getECCUEvents(sess, fromtimeTS, eventsSelector) aggregateECCUEvents(events) for e in events: l.info('The following annotation will be sent to mPulse API:') l.info(" Title: " + e.getAnnotationTitle()) l.info(" Text: " + e.getAnnotationText()) ts = e.getEventStartTime() l.info(" Start: " + ts + " (" + datetime.datetime.utcfromtimestamp( int(ts)).strftime('%Y-%m-%d %H:%M:%S') + " UTC)") if e.getEventEndTime() is not None: ts = e.getEventEndTime() l.info(" End: " + ts + " (" + datetime.datetime.utcfromtimestamp(int(ts)).strftime( '%Y-%m-%d %H:%M:%S') + " UTC)") mpulse.addAnnotation(mpulsetoken, e.getAnnotationTitle(), e.getAnnotationText(), e.getEventStartTime(), e.getEventEndTime()) else: mpulse.addAnnotation(mpulsetoken, e.getAnnotationTitle(), e.getAnnotationText(), e.getEventStartTime()) l.info('Pause ' + str(ANNOTATION_CREATE_DELAY) + ' seconds...') time.sleep(ANNOTATION_CREATE_DELAY) l.info("mpulse-annotator is stopping...")
def main(argv): usage = '''\ Usage: %s [-v] [-f] [-s sev] [-i path]* [path] Options: -v verbose (print all checked file names) -f enable checkers that yield many false positives -s sev only show problems with severity >= sev -i path ignore subdir or file path ''' % argv[0] try: gopts, args = getopt.getopt(argv[1:], 'vfs:i:') except getopt.GetoptError: print(usage) return 2 verbose = False severity = 1 ignore = [] falsepos = False for opt, val in gopts: if opt == '-v': verbose = True elif opt == '-f': falsepos = True elif opt == '-s': severity = int(val) elif opt == '-i': ignore.append(abspath(val)) if len(args) == 0: path = '.' elif len(args) == 1: path = args[0] else: print(usage) return 2 if not exists(path): print('Error: path %s does not exist' % path) return 2 count = defaultdict(int) for root, dirs, files in os.walk(path): # ignore subdirs in ignore list if abspath(root) in ignore: del dirs[:] continue for fn in files: fn = join(root, fn) if fn[:2] == './': fn = fn[2:] # ignore files in ignore list if abspath(fn) in ignore: continue ext = splitext(fn)[1] checkerlist = checkers.get(ext, None) if not checkerlist: continue if verbose: print('Checking %s...' % fn) try: with open(fn, 'r', encoding='utf-8') as f: lines = list(f) except (IOError, OSError) as err: print('%s: cannot open: %s' % (fn, err)) count[4] += 1 continue for checker in checkerlist: if checker.falsepositives and not falsepos: continue csev = checker.severity if csev >= severity: for lno, msg in checker(fn, lines): print('[%d] %s:%d: %s' % (csev, fn, lno, msg)) count[csev] += 1 if verbose: print() if not count: if severity > 1: print('No problems with severity >= %d found.' % severity) else: print('No problems found.') else: for severity in sorted(count): number = count[severity] print('%d problem%s with severity %d found.' % (number, 's' if number > 1 else '', severity)) return int(bool(count))
#------------------------------------------------ # CLI Options & Arguments #------------------------------------------------ #def main(): badbug = False # Enable to check CLI arguments #badbug = True # Enable to check CLI arguments debug = 0 query = 1 airport = '' airport2 = '' country = '' nmax = 0 try: opts, args = getopt.getopt(sys.argv[1:], ":chvd:i:j:l:m:n:x:", ["help", "version"]) except getopt.GetoptError : #print str(err) usage() sys.exit(2) if badbug : print ("opts: ", opts) print ("args: ", args) if not opts : if not args : usage(); sys.exit(); airport = args[0] query = 1 # Show Arrivals else : for opt, arg in opts:
finstr = finstr + " " + str(coeff) + varbs[chovar] + degs[chodegs] + " " + ops[chosops] # Strip extra characters finstr = finstr[1:-2] return finstr if __name__ == "__main__": import os, sys, getopt def usage(): print ('Usage: ' + os.path.basename(__file__) + ' limit latexify') print ('Options:') print ('\t -l limit, --limit=limit') print ('\t -t latex, --latex') sys.exit(2) try: opts, args = getopt.getopt(sys.argv[1:],"h:l:t",["help", "limit=", "latex"]) except getopt.GetoptError as err: print(err) usage() # extract parameters polylimit = None latexify = False for opt, arg in opts: if opt in ("-h", "--help"): usage() elif opt in ("-l", "--limit"): polylimit = arg elif opt in ("-t", "--latex"): latexify = True # check arguments if (polylimit is None):
Example: python3 /Users/wuaming/Desktop/TMConfuse/CodeConfuse/Confuse.py \ -i /Users/wuaming/Desktop/TMConfuse/TMConfuse \ -s /Users/wuaming/Desktop/TMConfuse/System_Frameworks_iOS \ -k /Users/wuaming/Desktop/TMConfuse/CodeConfuse/ignoreKey.txt \ -o /Users/wuaming/Desktop/TMConfuse/CodeConfuse """ print(help_info) if __name__ == '__main__': # 获取参数 options, args = getopt.getopt(sys.argv[1:], "hi:s:e:c:k:o:") input_dirs = None # 项目需要处理的主要文件所在的目录 system_dirs = None # 配置系统Framework文件的目录,一般用于做排除字典,避免替换系统关键字 exclusive_dirs = None # 用于存放不扫描处理的文件的目录,比如Swift文件目录 clean_dirs = None # 用于存放排除关键字的文件的目录,例如Pods下的目录,或者静态库(头文件修改后会出错) ignore_key_dir = None #用于存放需要过滤的key output_dir = None # 输出文件的目录,用于输出关键字、日志以及最后生成的混淆头文件的目录 for option, value in options: if option == "-i": input_dirs = value.split(',') elif option == "-s": system_dirs = value.split(',') elif option == "-e": exclusive_dirs = value.split(',') elif option == "-c":
#If you don't know how to get started using this script, start with: #python copy_english.py --help #from the command line of this directory. #You will need to have python installed. import os, sys, getopt #default to exporting from English to all other languages and not overwriting pre-existing files allLanguages = {'l_braz_por', 'l_english', 'l_french', 'l_german', 'l_polish', 'l_russian', 'l_spanish'} sourceLanguage = 'l_english' ignoreLanguages = set([]) overwrite = False try: options, extraargs = getopt.getopt(sys.argv[1:], "hi:os:",["help","ignore=","overwrite","source="]) except getopt.GetoptError: print('Invalid argument syntax in ' + sys.argv[0]) print('Valid arguments are -h, --help, -i, --ignore=, -o, --overwrite, -s, --source=') sys.exit(47) for opt, val in options: if opt in ("-i", "--ignore"): ignoreLanguages = set(val.split(",")) print('Ignoring the following languages:') print(ignoreLanguages) elif opt in ("-h", "--help"): print("-h, --help :") print(" See this help information.") print("-i, --ignore= :") print(" A comma-separated list of languages to not export to") print(" e.g. -i l_braz_por,l_french")
return None def nice_print(host_name, cert, cipher): subject = find_value(cert['subject'], 'commonName') notAfter = cert['notAfter'] issuer = find_value(cert['issuer'], 'commonName') l = (host_name, subject, issuer, notAfter) size = [len(i) for i in l] return size, l print("".join(word.ljust(35) for word in l)) if __name__ == '__main__': try: opts, args = getopt.getopt(sys.argv[1:], 'df:h', ['debug', 'full', 'help']) except getopt.GetoptError as e: print(e) print() usage() sys.exit(3) for opt, arg in opts: if opt in ('-h', '--help'): usage() sys.exit(0) elif opt in ('-d', '--debug'): debug_mode = True elif opt in ('-f', '--full'): full_chain_mode = True else: