def _option_parse(self, args): """Register program options :param args: program arguments (not used) :return: opt data """ usage = f"{self.pname} <OPTIONS>" pgm = self.pname self.parser = OPTEX.OptionParser(usage=usage, option_class=(OPTEX.Option), formatter=OPT.IndentedHelpFormatter( max_help_position=84, width=100)) group = OPT.OptionGroup(self.parser, 'Options', pgm) for _dest, _action, _default, _type, _metavar, _help in self._OPTIONS: if _type == '': group.add_option('', ('-' + _dest), action=_action, default=_default, dest=_dest, help=_help) else: group.add_option('', ('-' + _dest), action=_action, default=_default, dest=_dest, help=_help, type=_type, metavar=_metavar) self.parser.add_option_group(group) return self.parser.parse_args()[0]
def __init__(self, usage=None, option_list=None, option_class=Option, version=None, conflict_handler="error", description=None, formatter=None, add_help_option=True, prog=None, command_container=None, default_command="help", add_username_password_options=False): usage = usage or "%prog <command> [args] [--help]" self.container = command_container self.default_command = default_command self.command = None formatter = formatter or optparse.IndentedHelpFormatter( max_help_position=33) optparse.OptionParser.__init__(self, usage, option_list, option_class, version, conflict_handler, description, formatter, add_help_option, prog) if add_username_password_options: option_list = [ optparse.Option("--username", help="specify user"), optparse.Option("--password", help="specify password"), ] self._populate_option_list(option_list, add_help=False)
def main(): usage = 'python dumpPatches.py --inputFile race.result' fmt = optparse.IndentedHelpFormatter(max_help_position=50, width=100) parser = optparse.OptionParser(usage=usage, formatter=fmt) parser.add_option('--inputFile', dest='inputFile', help='Input File') (opts, args) = parser.parse_args() with open(opts.inputFile, 'r') as fin: sDirectoryName = opts.inputFile.split('.')[0] if not os.path.exists(sDirectoryName): os.makedirs(sDirectoryName) while True: line = fin.readline() if not line: break sFileName = os.path.join(sDirectoryName, line[:40]) #print line[:41] if not os.path.exists(sFileName): process = subprocess.Popen(['git', 'show', line[:40]], stdout=subprocess.PIPE, stderr=subprocess.PIPE) #print process.communicate()[1] with open(sFileName, 'w') as fout: fout.write(process.communicate()[0])
def main(): usage = """scholar.py [options] <query string> A command-line interface to Google Scholar.""" fmt = optparse.IndentedHelpFormatter(max_help_position=50, width=100) parser = optparse.OptionParser(usage=usage, formatter=fmt) parser.add_option('-a', '--author', help='Author name') parser.add_option('--csv', action='store_true', help='Print article data in CSV format (separator is "|")') parser.add_option('--csv-header', action='store_true', help='Like --csv, but print header line with column names') parser.add_option('--txt', action='store_true', help='Print article data in text format') parser.add_option('-c', '--count', type='int', help='Maximum number of results') parser.set_defaults(count=0, author='') options, args = parser.parse_args() if len(args) == 0: print 'Hrrrm. I need a query string.' sys.exit(1) query = ' '.join(args) if options.csv: csv(query, author=options.author, count=options.count) if options.csv_header: csv(query, author=options.author, count=options.count, header=True) if options.txt: txt(query, author=options.author, count=options.count)
def main(): usage = """anki-vim.py [options] Using VIM to generate textfiles which are directly anki-importable.""" fmt = optparse.IndentedHelpFormatter(max_help_position=50, width=100) parser = optparse.OptionParser(usage=usage, formatter=fmt) group = optparse.OptionGroup(parser, 'Arguments', """Options to specify card creation details. """) group.add_option('-d', '--deck', metavar='DECK', help='Name of the deck we write these cards for.') parser.add_option_group(group) # Parse options options, _ = parser.parse_args() # If no options are specified, print the help page. if len(sys.argv) == 1: parser.print_help() return 1 deck = options.deck deckpath = os.path.abspath("./decks") + "/" + deck content_added = True while content_added: # If a card is closed without content or changes, stop content_added = create_card.create_card(deckpath)
def init_opt_formatter(): def _format_option_string(option): ''' ('-o', '--option') -> -o, --format METAVAR''' opts = [] if option._short_opts: opts.append(option._short_opts[0]) if option._long_opts: opts.append(option._long_opts[0]) if len(opts) > 1: opts.insert(1, ', ') if option.takes_value(): opts.append(' %s' % option.metavar) return ''.join(opts) columns = compat_get_terminal_size().columns max_width = columns if columns else 80 max_help_position = 80 formatter = optparse.IndentedHelpFormatter( width=max_width, max_help_position=max_help_position) formatter.format_option_strings = _format_option_string return formatter
def main(): usage = """ format_time.py [options] """ fmt = optparse.IndentedHelpFormatter(max_help_position=50, width=100) parser = optparse.OptionParser(usage=usage, formatter=fmt) parser.add_option('-i', '--input', help='Input File') parser.add_option('-o', '--output', help='Output File') parser, args = parser.parse_args() if parser.input: event_json_read = ReadFile(parser.input) event_list = simplejson.loads(event_json_read) result = {} formatMiss = 0 for i in range(len(event_list)): if len(event_list[i]['start_time']) != 0: try: event_list[i]['start_time'] = format_time( event_list[i]['start_time']) except ValueError, e: event_list[i]['start_time'] = '0000-00' formatMiss += 1 print e if len(event_list[i]['end_time']) != 0: try: event_list[i]['end_time'] = format_time( event_list[i]['end_time']) except ValueError, e: event_list[i]['start_time'] = '0000-00' formatMiss += 1 print e
def main(): usage = """google-apps-scraper.py [options] web scraper for google apps lists Examples: """ fmt = optparse.IndentedHelpFormatter(max_help_position=50, width=100) parser = optparse.OptionParser(usage=usage, formatter=fmt) group = optparse.OptionGroup(parser, 'Google apps query arguments', 'e.g. categories to search for, path of output .csv file') group.add_option('-c', '--category', metavar='CATEGORY', default=None, help="category of app (e.g. 'AUTO_AND_VEHICLES'). fetches all categories by default.") group.add_option('-f', '--output-file', metavar='OUTPUT_FILE', default='apps.csv', help="output .csv file") parser.add_option_group(group) options, _ = parser.parse_args() if len(sys.argv) == 1: parser.print_help() return 1 # crawl all categories, save results in .csv file with open(options.output_file, 'wb') as csv_file: writer = csv.writer(csv_file) first_row = False category_list = [] # if a category is specified, stick to it, otherwise fetch all of them if options.category: category_list.append(options.category) else: category_list = GOOGLE_APS_CATS for cat in category_list: # build the url for the category url = GOOGLE_APS_URL_PREFIX + "/store/apps/category/" + cat + GOOGLE_APS_URL_APP_COLLECTION + "?hl=en" # get the webpage page = requests.get(url, headers=headers) # extract the raw html text into an object which can be parsed html_code = html.fromstring(page.content) # cycle through each app for app in html_code.cssselect("div.details a.title"): app = parse_app(app.attrib['title'], app.attrib['href']) app['category'] = cat try: # write a row of keys first if not first_row: writer.writerow(app.keys()) first_row = True writer.writerow(app.values()) except: print("launchpad-scraper.py::main() : [ERROR] unknown error parsing JSON")
def record_cmd(argv): parser = optparse.OptionParser(usage="rosbag record TOPIC1 [TOPIC2 TOPIC3 ...]", description="Record a bag file with the contents of specified topics.", formatter=optparse.IndentedHelpFormatter()) parser.add_option("-a", "--all", dest="all", default=False, action="store_true", help="record all topics") parser.add_option("-e", "--regex", dest="regex", default=False, action="store_true", help="match topics using regular expressions") parser.add_option("-x", "--exclude", dest="exclude_regex", default="", action="store", help="exclude topics matching the follow regular expression (subtracts from -a or regex)") parser.add_option("-q", "--quiet", dest="quiet", default=False, action="store_true", help="suppress console output") parser.add_option("-o", "--output-prefix", dest="prefix", default=None, action="store", help="prepend PREFIX to beginning of bag name (name will always end with date stamp)") parser.add_option("-O", "--output-name", dest="name", default=None, action="store", help="record to bag with name NAME.bag") parser.add_option( "--split", dest="split", default=False, callback=handle_split, action="callback", help="split the bag when maximum size or duration is reached") parser.add_option( "--size", dest="size", type='int', action="store", help="record a bag of maximum size SIZE", metavar="SIZE") parser.add_option( "--duration", dest="duration", type='string',action="store", help="record a bag of maximum duration DURATION in seconds, unless 'm', or 'h' is appended.", metavar="DURATION") parser.add_option("-b", "--buffsize", dest="buffsize", default=256, type='int', action="store", help="use an internal buffer of SIZE MB (Default: %default, 0 = infinite)", metavar="SIZE") parser.add_option("--chunksize", dest="chunksize", default=768, type='int', action="store", help="Advanced. Record to chunks of SIZE KB (Default: %default)", metavar="SIZE") parser.add_option("-l", "--limit", dest="num", default=0, type='int', action="store", help="only record NUM messages on each topic") parser.add_option( "--node", dest="node", default=None, type='string',action="store", help="record all topics subscribed to by a specific node") parser.add_option("-j", "--bz2", dest="compression", default=None, action="store_const", const='bz2', help="use BZ2 compression") parser.add_option("--lz4", dest="compression", action="store_const", const='lz4', help="use LZ4 compression") (options, args) = parser.parse_args(argv) if len(args) == 0 and not options.all and not options.node: parser.error("You must specify a topic name or else use the '-a' option.") if options.prefix is not None and options.name is not None: parser.error("Can't set both prefix and name.") recordpath = roslib.packages.find_node('rosbag', 'record') if not recordpath: parser.error("Cannot find rosbag/record executable") cmd = [recordpath[0]] cmd.extend(['--buffsize', str(options.buffsize)]) cmd.extend(['--chunksize', str(options.chunksize)]) if options.num != 0: cmd.extend(['--limit', str(options.num)]) if options.quiet: cmd.extend(["--quiet"]) if options.prefix: cmd.extend(["-o", options.prefix]) if options.name: cmd.extend(["-O", options.name]) if options.exclude_regex: cmd.extend(["--exclude", options.exclude_regex]) if options.all: cmd.extend(["--all"]) if options.regex: cmd.extend(["--regex"]) if options.compression: cmd.extend(["--%s" % options.compression]) if options.split: if not options.duration and not options.size: parser.error("Split specified without giving a maximum duration or size") cmd.extend(["--split"]) if options.duration: cmd.extend(["--duration", options.duration]) if options.size: cmd.extend(["--size", str(options.size)]) if options.node: cmd.extend(["--node", options.node]) cmd.extend(args) # Better way of handling it than os.execv # This makes sure stdin handles are passed to the process. subprocess.call(cmd)
def standalone_help(self): help_text = self.name_with_arguments().ljust( len(self.name_with_arguments()) + 3) + self.help_text + "\n\n" if self.long_help: help_text += "%s\n\n" % self.long_help help_text += self.option_parser.format_option_help( optparse.IndentedHelpFormatter()) return help_text
def formatDescription(self): formatter = optparse.IndentedHelpFormatter(width=80) formatter.store_option_strings(self) formatter.indent() lines = [formatter.format_description(self.description)] formatter.dedent() return [formatter.format_heading("Description")] + lines
def main(args=None): if args is None: args = sys.argv parser = optparse.OptionParser( formatter=optparse.IndentedHelpFormatter(max_help_position=50)) parser.add_option('--verbose', action='store_true', default=False) parser.add_option('--quiet', action='store_true', default=False) (options, args) = parser.parse_args(args) setup_logging(options) if len(args) != 2: logging.error("Usage: ./cli_tests.py path_to_botan_cli") return 1 if os.access(args[1], os.X_OK) != True: logging.error("Could not access/execute %s", args[1]) return 2 global CLI_PATH CLI_PATH = args[1] start_time = time.time() cli_compress_tests() cli_psk_db_tests() cli_help_tests() cli_is_prime_tests() cli_factor_tests() cli_mod_inverse_tests() cli_base64_tests() cli_hex_tests() cli_gen_prime_tests() cli_hash_tests() cli_rng_tests() cli_bcrypt_tests() cli_gen_dl_group_tests() cli_pk_workfactor_tests() cli_ec_group_info_tests() cli_key_tests() cli_cc_enc_tests() cli_timing_test_tests() cli_asn1_tests() cli_speed_tests() cli_tls_ciphersuite_tests() cli_tls_socket_tests() end_time = time.time() print("Ran %d tests with %d failures in %.02f seconds" % ( TESTS_RUN, TESTS_FAILED, end_time - start_time)) if TESTS_FAILED > 0: return 1 return 0
def __init__(self): help_fmt = optparse.IndentedHelpFormatter() self.optparser = _OptionParserEx(prog=self.name, add_help_option=False, formatter=help_fmt) self.optparser.add_option('--help', '-h', action='store_true', help='show this help message and exit') self.optparser.add_options(self.options)
def __init__(_): ihf = optparse.IndentedHelpFormatter( 2, 60, 120) # , formatter = optparse.TitledHelpFormatter(), optparse.OptionParser.__init__(_, add_help_option=False, prog=APPNAME, usage="python tp <tags and options>", description=APPSTR, version=VERSION, formatter=ihf)
def formatUsage(self): formatter = optparse.IndentedHelpFormatter(width=80) formatter.store_option_strings(self) formatter.indent() lines = [ formatter._format_text(self.expand_prog_name(self.usage)) + "\n" ] formatter.dedent() return [formatter.format_heading("Usage")] + lines
def search_gscholar(): usage_str = """ scholar.py [options] <query string> A command-line interface to Google Scholar. Text output will show on the terminal screen. """ fmt = optparse.IndentedHelpFormatter(max_help_position=50, width=100) parser = optparse.OptionParser(usage=usage_str, formatter=fmt) parser.add_option('-a', '--author', help='Author name') parser.add_option( '--csv', action='store_true', help='Print article data in CSV format (separator is "|")') parser.add_option( '--csv-header', action='store_true', help='Like --csv, but print header line with column names') parser.add_option('--txt', action='store_true', help='Print article data in text format') parser.add_option('-c', '--count', type='int', help='Maximum number of results') parser.add_option('-y', '--year', type='int', help='Search for articles published since year xxxx') parser.set_defaults(count=0, author='') options, args = parser.parse_args() if len(args) == 0: print('Usage: ' + usage_str) sys.exit(1) query = ' '.join(args) params = { 'author': options.author, 'count': options.count, 'year_lo': options.year } querier = ScholarQuerier(params) articles = querier.query(query) if options.count > 0: articles = articles[:options.count] print('Number of articles retrieved: {}'.format(len(articles))) for art in articles: print("---------------------------------------") art.as_concise_org_print() print("----------------------------\n")
def terminal_formatter(): max_width = 80 max_help_position = 80 # No need to wrap help messages if we're on a wide console columns = get_terminal_size()[0] if columns: max_width = columns fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position) return fmt
def main(): usage = """scholar.py [options] <query string> A command-line interface to Google Scholar.""" fmt = optparse.IndentedHelpFormatter(max_help_position=50, width=100) parser = optparse.OptionParser(usage=usage, formatter=fmt) parser.add_option('-a', '--author', help='Author name') parser.add_option('--csv', action='store_true', help='Print article data in CSV format (separator is "|")') parser.add_option('--csv-header', action='store_true', help='Like --csv, but print header line with column names') parser.add_option('--txt', action='store_true', help='Print article data in text format') parser.add_option('--bibtex', action='store_true', help='Print article data in bibtex format') parser.add_option('--endnote', action='store_true', help='Print article data in endnote format') parser.add_option('--refman', action='store_true', help='Print article data in refman format') parser.add_option('--wenxianwang', action='store_true', help='Print article data in wenxianwang format') parser.add_option('-c', '--count', type='int', help='Maximum number of results') parser.set_defaults(count=0, author='') options, args = parser.parse_args() if len(args) == 0: print 'Hrrrm. I need a query string.' sys.exit(1) query = ' '.join(args) if options.csv: csv(query, author=options.author, count=options.count) elif options.csv_header: csv(query, author=options.author, count=options.count, header=True) elif options.bibtex: citation(query, author=options.author, count=options.count, cite_format=CiteFormat.BIBTEX) elif options.endnote: citation(query, author=options.author, count=options.count, cite_format=CiteFormat.ENDNOTE) elif options.refman: citation(query, author=options.author, count=options.count, cite_format=CiteFormat.REFMAN) elif options.wenxianwang: citation(query, author=options.author, count=options.count, cite_format=CiteFormat.WENXIANWANG) else: txt(query, author=options.author, count=options.count)
def test_old(self): old_formatter = optparse.IndentedHelpFormatter(width=50) parser = i18n_optparse.OptionParser(description="test", formatter=old_formatter) parser.add_option("-t", "--test", dest="test", default=None, help="このシステム用に権利があるレポジトリのがあるレポジトリの一覧表示") fh = parser.format_option_help() # This case, width this formatter, this string, and this width, # the old formatter would split in a multibyte char, creating # a string that doesn't decode to utf8. So verify this still # happens with the old string self.assertRaises(UnicodeDecodeError, fh.decode, "utf8")
def main(): usage = """scholar.py [options] <query string> A command-line interface to Google Scholar. Example: scholar.py -c 1 --txt --author=einstein --year=1960 quantum""" fmt = optparse.IndentedHelpFormatter(max_help_position=50, width=100) parser = optparse.OptionParser(usage=usage, formatter=fmt) parser.add_option('-a', '--author', help='Author name') parser.add_option('-y', '--year', type='int', help='Year of publication') parser.add_option('--csv', action='store_true', help='Print article data in CSV form (separator is "|")') parser.add_option('--csv-header', action='store_true', help='Like --csv, but print header with column names') parser.add_option('--txt', action='store_true', help='Print article data in text format') parser.add_option('-c', '--count', type='int', help='Maximum number of results') parser.set_defaults(count=0, author='') options, args = parser.parse_args() # Show help if we have neither keyword search nor author name if len(args) == 0 and options.author == '': parser.print_help() return 1 query = ' '.join(args) if options.csv: csv(query, author=options.author, year=options.year, count=options.count) elif options.csv_header: csv(query, author=options.author, year=options.year, count=options.count, header=True) else: txt(query, author=options.author, year=options.year, count=options.count) return 0
def main(): usage = "youtubestat.py [options] <query string>" fmt = optparse.IndentedHelpFormatter(max_help_position=50, width=100) parser = optparse.OptionParser(usage=usage, formatter=fmt) group = optparse.OptionGroup( parser, 'Query arguments', 'These options define search query arguments and parameters.') group.add_option( '-C', '--category', metavar='CATEGORY', default=None, help='Indicate the category, e.g. news, sports, education, etc.') group.add_option('-N', '--topN', metavar='TOPN', default=None, help='Indicate the number of channels to show') group.add_option( '-L', '--lang', metavar='LANGUAGE', default=None, help='Indicate the channel language, e.g. en, zh, es, etc.') group.add_option( '-F', '--fmt', metavar='FORMAT', default=None, help='Indicate the output format, e.g. csv, txt, md, etc.') parser.add_option_group(group) options, _ = parser.parse_args() # Show help if we have neither keyword search nor author name if len(sys.argv) == 1: parser.print_help() return 1 URL = "https://www.kedoo.com/youtube/en/top-channels.html?period=2017-11-01&category=2&lang=en" # URL = "https://www.baidu.com/s?wd=news&rsv_spt=1&rsv_iqid=0xfd03b200002f9eff&issp=1&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&tn=baiduhome_pg&rsv_enter=1&rsv_dl=ib" html = get_HTML(URL) res = get_data(html) # print("res === ", res) output(res, topN=int(options.__dict__["topN"]), fmt=options.__dict__["fmt"]) return 0
def getCommandLineParametersParser(): """ Returns the command line parameters parser. :return: Parser. :rtype: Parser """ parser = optparse.OptionParser(formatter=optparse.IndentedHelpFormatter( indent_increment=2, max_help_position=8, width=128, short_first=1), add_help_option=None) parser.add_option("-h", "--help", action="help", help="'Display this help message and exit.'") parser.add_option("-i", "--input", action="store", type="string", dest="input", default="zbrush", help="'Input textures format ( mari, zbrush, mudbox )'.") parser.add_option( "-o", "--output", action="store", type="string", dest="output", default="mari", help="'Output textures format ( mari, zbrush, mudbox )'.") parser.add_option("-n", "--name", action="store", type="string", dest="name", help="'Name prefix ( \"\" to strip name ).") parser.add_option("-p", "--preview", action="store_true", default=False, dest="preview", help="'Preview changes only.") return parser
def formatArgsHelp(self): formatter = optparse.IndentedHelpFormatter(width=80) formatter.indent() for opt in self.args_list: metavar = opt.metavar or opt.dest.upper() strings = metavar.upper() formatter.option_strings[opt] = strings formatter.dedent() formatter.help_position = 31 formatter.help_width = formatter.width - formatter.help_position formatter.indent() lines = [formatter.format_option(opt) for opt in self.args_list] formatter.dedent() return [formatter.format_heading("Arguments")] + lines
def init_parser(banner=None): """ Create an OptionParser object and returns its parser member. Keyword arguments: banner Optional version banner to display for --version Returns: OptionParser object. """ fmt = optparse.IndentedHelpFormatter(indent_increment=4, max_help_position=32, width=77, short_first=1) parser = optparse.OptionParser(formatter=fmt, version=banner) return parser
def __init__(self, usage=None, option_list=None, option_class=Option, version=None, conflict_handler="error", description=None, formatter=None, add_help_option=True, prog=None, command_container=None, default_command="help", add_username_password_options=False, default_profile="", configuration_directory="/etc"): usage = usage or "%prog <command> [args] [--help]" self.container = command_container self.default_command = default_command self.command = None formatter = formatter or optparse.IndentedHelpFormatter( max_help_position=33) optparse.OptionParser.__init__(self, usage, option_list, option_class, version, conflict_handler, description, formatter, add_help_option, prog) if add_username_password_options: self._add_opts(["--username", "specify user"], ["--password", "specify password"]) if default_profile: self.default_profile = default_profile self._add_opts([ "--profile", "specify profile (default: {0})".format(self.default_profile) ]) else: self.default_profile = "" self.configuration_directory = configuration_directory
def formatOptionsHelp(self): formatter = optparse.IndentedHelpFormatter(width=80) formatter.indent() for opt in self.option_list: strings = formatter.format_option_strings(opt) formatter.option_strings[opt] = strings formatter.dedent() formatter.help_position = 31 formatter.help_width = formatter.width - formatter.help_position formatter.indent() lines = [formatter.format_option(opt) for opt in self.option_list] formatter.dedent() if len(lines) > 0: return [formatter.format_heading("Options")] + lines else: return []
def main(): usage = """ htmlEscape.py -i <INPUT File> -m <Escape or Unescape> \n Example: python htmlEscape.py -i demo.txt -m e[, -o output_file_name] """ fmt = optparse.IndentedHelpFormatter(max_help_position=50, width=100) parser = optparse.OptionParser(usage=usage, formatter=fmt) parser.add_option('-i', '--input', help='Input File') parser.add_option('-o', '--output', help='Output Dir') parser.add_option( '-m', '--mod', help= 'Choose Escape(&=>&) Please type -m e or \n\r Unescape(&=>&) please type -m u' ) options, args = parser.parse_args() if not options.input: print 'Hrrrm....You’re looking swell, Dolly\n but i need a input filename' sys.exit(1) elif not options.mod: print u'请选择要执行 &=>& 这类操作还是 &=>& 具体帮助请使用 "-h" 参数' sys.exit(1) elif not options.output: if options.mod == 'e': escape_html(options.input) elif options.mod == 'u': unescape_html(options.input) else: print 'Error! Wrong Args, For more please type python htmlEscape.py -h' sys.exit(1) elif options.output: if options.mod == 'e': escape_html(options.input, options.output) elif options.mod == 'u': unescape_html(options.input, options.output) else: print 'Error! Wrong Args, For more please type python htmlEscape.py -h' sys.exit(1) else: print "Hrrm....You're looking ...Hrrrm...,Bad args!" sys.exit(1)
def main(): usage = """ """ fmt = optparse.IndentedHelpFormatter(max_help_position=50, width=100) parser = optparse.OptionParser(usage=usage, formatter=fmt) parser.add_option('-i', '--input', help='Input file') parser.add_option('-o','--output', help='Output file') options = parser.parse_args() if not options.input: print 'I need an input filename' sys.exit(1) elif not options.output: print 'I need an output filename' sys.exit(1) else: get_cited_info()
def main(): usage = """ getLostCredit.py [options] """ fmt = optparse.IndentedHelpFormatter(max_help_position=50, width=100) parser = optparse.OptionParser(usage=usage, formatter=fmt) parser.add_option('-o', '--output', help='Output file') parser.set_defaults(output="loseCredit.json") options, args = parser.parse_args() #if len(options) == 0: # print 'Hrrrm. I need a query string.' # sys.exit(1) initurl = "http://shixin.court.gov.cn/detail?id=" id = 2000 while id <= 50000: print id data = download(initurl + str(id)) if data <> '' and data: saveJson(data, options.output) print data id += 1
def main(): usage = 'python parseGitLog.py --inputFile log.txt --keyWord xxx' fmt = optparse.IndentedHelpFormatter(max_help_position=50, width=100) parser = optparse.OptionParser(usage=usage, formatter=fmt) parser.add_option('--inputFile', dest='inputFile', help='Input File') # parser.add_option('--keyWord', dest='keyWord', help='Key Words') reComment = re.compile(r'^ [^\s]') (opts, args) = parser.parse_args() numCommits = 0 hashCommitSet = set() strCurrentCommit = "" with open(opts.inputFile, 'r', encoding='latin-1') as fin: while True: line = fin.readline() if not line: break match = reCOMMIT.match(line) if match: numCommits += 1 strCurrentCommit = match.group(1) continue match = reComment.match(line) if match: if is_useful_commit(line): if strCurrentCommit: hashCommitSet.add(strCurrentCommit) print("Total number bug is %d" % len(hashCommitSet))