当前位置: 首页>>代码示例>>Python>>正文


Python pywikibot.handleArgs函数代码示例

本文整理汇总了Python中pywikibot.handleArgs函数的典型用法代码示例。如果您正苦于以下问题:Python handleArgs函数的具体用法?Python handleArgs怎么用?Python handleArgs使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了handleArgs函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: pre

def pre(taskid=-1, lock=None, sites=[], continuous=False, main=None):
    """
    Return argument list, site object, and configuration of the script.
    This function also handles default arguments, generates lockfile
    and halt the script if lockfile exists before.
    """
    import imp

    global info
    info["main"] = main == "__main__"
    if continuous:
        lock = False
    pywikibot.handleArgs("-log")
    pywikibot.output("start task #%s at %s" % (taskid, getTime()))
    info["taskid"] = taskid
    info["lock"] = lock
    info["lockfile"] = simplifypath([os.environ["WPROBOT_DIR"], "tmp", info["basescript"] + ".lock"])
    info["continuous"] = continuous
    if os.path.exists(info["lockfile"]) and lock:
        error("lockfile found. unable to execute the script.")
        if info["main"]:
            pywikibot.stopme()
        sys.exit(ExitCode.LockFileError)

    open(info["lockfile"], "w").close()

    args = pywikibot.handleArgs()  # must be called before Site()
    site = pywikibot.Site()
    info["site"] = site

    confpath = simplifypath([os.environ["WPROBOT_DIR"], "conf", info["basescript"]])

    module = imp.load_source("conf", confpath) if os.path.exists(confpath) else None
    return args, site, module
开发者ID:nullzero,项目名称:wprobot,代码行数:34,代码来源:__init__.py

示例2: main

def main():


    db = oursql.connect(db='wikidatawiki_p',
        host="wikidatawiki-p.rrdb.toolserver.org",
        read_default_file=os.path.expanduser("~/.my.cnf"),
        charset=None,
        use_unicode=False
    )


    pywikibot.handleArgs()

    cur = db.cursor()
    cur.execute(query)
    data=cur.fetchall()
    for row in data:
        check_item(row[0])
    global REPORT
    global DUPES
    rfd() #before dupes
    pg = pywikibot.Page(wikidata, 'User:Legobot/Dupes')
    pg.put(REPORT, 'Bot: Updating list of dupes')
    #save dupes locally for null edits
    fname = 'wd_null.txt'
    if os.path.exists(fname):
        with open(fname, 'r') as f:
            old = f.read()
    else:
        old = ''
    new = old + DUPES
    with open(fname, 'w') as f:
        f.write(new)
    print 'Saved dupe file'
开发者ID:RileyHuntley,项目名称:wikidata,代码行数:34,代码来源:wikidata_blank_items.py

示例3: main

def main():
    gen = pagegenerators.GeneratorFactory()
    commandline_claims = list()
    for arg in pywikibot.handleArgs():
        if gen.handleArg(arg):
            continue
        commandline_claims.append(arg)
    if len(commandline_claims) % 2:
        raise ValueError  # or something.
    claims = list()

    repo = pywikibot.Site().data_repository()

    for i in xrange (0, len(commandline_claims), 2):
        claim = pywikibot.Claim(repo, commandline_claims[i])
        if claim.getType() == 'wikibase-item':
            target = pywikibot.ItemPage(repo, commandline_claims[i+1])
        elif claim.getType() == 'string':
            target = commandline_claims[i+1]
        else:
            raise NotImplementedError("%s datatype is not yet supported by claimit.py" % claim.getType())
        claim.setTarget(target)
        claims.append(claim)

    generator = gen.getCombinedGenerator()
    if not generator:
        # FIXME: Should throw some help
        return
    
    bot = ClaimRobot(generator, claims)
    bot.run()
开发者ID:pywikibot,项目名称:core-migration-example,代码行数:31,代码来源:claimit.py

示例4: main

def main(*args):
    global bot
    # Disable cosmetic changes because we don't want to modify any page
    # content, so that we don't flood the histories with minor changes.
    config.cosmetic_changes = False
    #page generator
    gen = None
    genFactory = pagegenerators.GeneratorFactory()
    redirs = False
    # If the user chooses to work on a single page, this temporary array is
    # used to read the words from the page title. The words will later be
    # joined with spaces to retrieve the full title.
    pageTitle = []
    for arg in pywikibot.handleArgs(*args):
        if genFactory.handleArg(arg):
            continue
        if arg == '-redir':
            redirs = True
        else:
            pageTitle.append(arg)
    pywikibot.Site().login()
    gen = genFactory.getCombinedGenerator()
    if not gen:
        if pageTitle:
            # work on a single page
            page = pywikibot.Page(pywikibot.Link(' '.join(pageTitle)))
            gen = iter([page])
        else:
            pywikibot.showHelp()
            return
    preloadingGen = pagegenerators.PreloadingGenerator(gen)
    bot = TouchBot(preloadingGen, redirs)
    bot.run()
开发者ID:Aaron1011,项目名称:pywikibot-core,代码行数:33,代码来源:touch.py

示例5: main

def main():
    featured = False
    gen = None

    # Process global args and prepare generator args parser
    local_args = pywikibot.handleArgs()
    genFactory = pagegenerators.GeneratorFactory()

    for arg in local_args:
        if arg == '-featured':
            featured = True
        else:
            genFactory.handleArg(arg)

    mysite = pywikibot.Site()
    if mysite.sitename() == 'wikipedia:nl':
        pywikibot.output(
            u'\03{lightred}There is consensus on the Dutch Wikipedia that bots should not be used to fix redirects.\03{default}')
        sys.exit()

    if featured:
        featuredList = i18n.translate(mysite, featured_articles)
        ref = pywikibot.Page(pywikibot.Site(), featuredList)
        gen = pagegenerators.ReferringPageGenerator(ref)
        gen = pagegenerators.NamespaceFilterPageGenerator(gen, [0])
    if not gen:
        gen = genFactory.getCombinedGenerator()
    if gen:
        for page in pagegenerators.PreloadingGenerator(gen):
            workon(page)
    else:
        pywikibot.showHelp('fixing_redirects')
开发者ID:APerson241,项目名称:pywikibot-core,代码行数:32,代码来源:fixing_redirects.py

示例6: main

def main():
    genFactory = pagegenerators.GeneratorFactory()
    commandline_arguments = list()
    templateTitle = u''
    for arg in pywikibot.handleArgs():
        if arg.startswith('-template'):
            if len(arg) == 9:
                templateTitle = pywikibot.input(
                    u'Please enter the template to work on:')
            else:
                templateTitle = arg[10:]
        elif genFactory.handleArg(arg):
            continue
        else:
            commandline_arguments.append(arg)

    if len(commandline_arguments) % 2 or not templateTitle:
        raise ValueError  # or something.
    fields = dict()

    for i in xrange(0, len(commandline_arguments), 2):
        fields[commandline_arguments[i]] = commandline_arguments[i + 1]
    if templateTitle:
        gen = pagegenerators.ReferringPageGenerator(
            pywikibot.Page(pywikibot.getSite(),
                           "Template:%s" % templateTitle),
            onlyTemplateInclusion=True)
    else:
        gen = genFactory.getCombinedGenerator()
    if not gen:
        # TODO: Build a transcluding generator based on templateTitle
        return

    bot = HarvestRobot(gen, templateTitle, fields)
    bot.run()
开发者ID:Rodehi,项目名称:GFROS,代码行数:35,代码来源:harvest_template.py

示例7: main

def main():
    '''
    Main loop. Get a generator and options.
    '''
    generator = None
    parent = u''
    basename = u''
    always = False

    # Process global args and prepare generator args parser
    local_args = pywikibot.handleArgs()
    genFactory = pagegenerators.GeneratorFactory()

    for arg in local_args:
        if arg == '-always':
            always = True
        elif arg.startswith('-parent:'):
            parent = arg[len('-parent:'):].strip()
        elif arg.startswith('-basename'):
            basename = arg[len('-basename:'):].strip()
        else:
            genFactory.handleArg(arg)

    generator = genFactory.getCombinedGenerator()
    if generator:
        for page in generator:
            createCategory(page, parent, basename)
    else:
        pywikibot.output(u'No pages to work on')

    pywikibot.output(u'All done')
开发者ID:APerson241,项目名称:pywikibot-core,代码行数:31,代码来源:create_categories.py

示例8: main

def main():
    genFactory = pagegenerators.GeneratorFactory()
    pageName = ''
    summary = None
    always = False
    undelete = False
    generator = None

    # read command line parameters
    local_args = pywikibot.handleArgs()
    mysite = pywikibot.Site()

    for arg in local_args:
        if arg == '-always':
            always = True
        elif arg.startswith('-summary'):
            if len(arg) == len('-summary'):
                summary = pywikibot.input(u'Enter a reason for the deletion:')
            else:
                summary = arg[len('-summary:'):]
        elif arg.startswith('-images'):
            pywikibot.output('\n\03{lightred}-image option is deprecated. '
                             'Please use -imageused instead.\03{default}\n')
            local_args.append('-imageused' + arg[7:])
        elif arg.startswith('-undelete'):
            undelete = True
        else:
            genFactory.handleArg(arg)
            found = arg.find(':') + 1
            if found:
                pageName = arg[found:]

        if not summary:
            if pageName:
                if arg.startswith('-cat') or arg.startswith('-subcats'):
                    summary = i18n.twtranslate(mysite, 'delete-from-category',
                                               {'page': pageName})
                elif arg.startswith('-links'):
                    summary = i18n.twtranslate(mysite, 'delete-linked-pages',
                                               {'page': pageName})
                elif arg.startswith('-ref'):
                    summary = i18n.twtranslate(mysite, 'delete-referring-pages',
                                               {'page': pageName})
                elif arg.startswith('-imageused'):
                    summary = i18n.twtranslate(mysite, 'delete-images',
                                               {'page': pageName})
            elif arg.startswith('-file'):
                summary = i18n.twtranslate(mysite, 'delete-from-file')
    generator = genFactory.getCombinedGenerator()
    # We are just deleting pages, so we have no need of using a preloading
    # page generator to actually get the text of those pages.
    if generator:
        if summary is None:
            summary = pywikibot.input(u'Enter a reason for the %sdeletion:'
                                      % ['', 'un'][undelete])
        bot = DeletionRobot(generator, summary, always, undelete)
        bot.run()
    else:
        # Show help text from the top of this file
        pywikibot.showHelp()
开发者ID:APerson241,项目名称:pywikibot-core,代码行数:60,代码来源:delete.py

示例9: main

def main(args):
    """
    Main loop. Get a generator and options. Work on all images in the generator.

    """
    generator = None
    onlyFilter = False
    onlyUncat = False
    genFactory = pagegenerators.GeneratorFactory()

    global search_wikis
    global hint_wiki

    site = pywikibot.getSite(u'commons', u'commons')
    pywikibot.setSite(site)
    for arg in pywikibot.handleArgs():
        if arg == '-onlyfilter':
            onlyFilter = True
        elif arg == '-onlyuncat':
            onlyUncat = True
        elif arg.startswith('-hint:'):
            hint_wiki = arg[len('-hint:'):]
        elif arg.startswith('-onlyhint'):
            search_wikis = arg[len('-onlyhint:'):]
        else:
            genFactory.handleArg(arg)

    generator = genFactory.getCombinedGenerator()
    if not generator:
        generator = pagegenerators.CategorizedPageGenerator(
            catlib.Category(site, u'Category:Media needing categories'),
            recurse=True)
    initLists()
    categorizeImages(generator, onlyFilter, onlyUncat)
    pywikibot.output(u'All done')
开发者ID:SirComputer1,项目名称:SCBot,代码行数:35,代码来源:imagerecat.py

示例10: main

def main():
    local_args = pywikibot.handleArgs()
    cache_paths = None
    delete = False
    command = None

    for arg in local_args:
        if command == '':
            command = arg
        elif arg == '-delete':
            delete = True
        elif arg == '-password':
            command = 'has_password(entry)'
        elif arg == '-c':
            if command:
                pywikibot.error('Only one command may be executed.')
                exit(1)
            command = ''
        else:
            if not cache_paths:
                cache_paths = [arg]
            else:
                cache_paths.append(arg)

    func = None

    if not cache_paths:
        cache_paths = ['apicache', 'tests/apicache']

        # Also process the base directory, if it isnt the current directory
        if os.path.abspath(os.getcwd()) != pywikibot.config2.base_dir:
            cache_paths += [
                os.path.join(pywikibot.config2.base_dir, 'apicache')]

        # Also process the user home cache, if it isnt the config directory
        if os.path.expanduser('~/.pywikibot') != pywikibot.config2.base_dir:
            cache_paths += [
                os.path.join(os.path.expanduser('~/.pywikibot'), 'apicache')]

    if delete:
        action_func = lambda entry: entry._delete()
    else:
        action_func = lambda entry: pywikibot.output(entry)

    if command:
        try:
            command_func = eval('lambda entry: ' + command)
        except:
            pywikibot.exception()
            pywikibot.error(u'Can not compile command: %s' % command)
            exit(1)

        func = lambda entry: command_func(entry) and action_func(entry)
    else:
        func = action_func

    for cache_path in cache_paths:
        if len(cache_paths) > 1:
            pywikibot.output(u'Processing %s' % cache_path)
        process_entries(cache_path, func)
开发者ID:skamithi,项目名称:pywikibot-core,代码行数:60,代码来源:cache.py

示例11: main

def main():
	
	selectedSet = None
	always = False
	idProp = insertProp = filename = False
	
	# Handles command-line arguments for pywikibot.
	for arg in pywikibot.handleArgs():
		if arg.startswith('-identifier:'):
			idProp = arg.replace('-identifier:', '')
		if arg.startswith('-insert:'):
			insertProp = arg.replace('-insert:', '')
		if arg.startswith('-file:'):
			filename = arg.replace('-file:', '')
		if arg.startswith('-always'):
			always=True
	
	if idProp == None or insertProp == None or filename == None:
		pywikibot.output('All arguments are required!')
		return
	
	matchDict = {}
	with open(filename, 'r') as f:
		reader = csv.reader(f, delimiter=";")
		for row in reader:
			matchDict[row[0]] = row[1]
		
	bot = PropertyBot(always=always, idProp=idProp, insertProp=insertProp, matchDict=matchDict)
	bot.run()
开发者ID:EAGLE-BPN,项目名称:eagle-wiki,代码行数:29,代码来源:insert-property.py

示例12: main

def main(*args):
    gen = None
    notitle = False
    page_get = False

    # Process global args and prepare generator args parser
    local_args = pywikibot.handleArgs(*args)
    genFactory = GeneratorFactory()

    for arg in local_args:
        if arg == '-notitle':
            notitle = True
        elif arg == '-get':
            page_get = True
        else:
            genFactory.handleArg(arg)

    gen = genFactory.getCombinedGenerator()
    if gen:
        for i, page in enumerate(gen, start=1):
            if not notitle:
                pywikibot.stdout("%4d: %s" % (i, page.title()))
            if page_get:
                # TODO: catch exceptions
                pywikibot.output(page.text, toStdout=True)
    else:
        pywikibot.showHelp()
开发者ID:APerson241,项目名称:pywikibot-core,代码行数:27,代码来源:listpages.py

示例13: main

def main():
    countrycode = u''
    lang = u''
    municipality = u''
    minimum = 15
    conn = None
    cursor = None
    # Connect database, we need that
    (conn, cursor) = connect_to_monuments_database()

    for arg in pywikibot.handleArgs():
        option, sep, value = arg.partition(':')
        if option == '-countrycode':
            countrycode = value
        elif option == '-langcode':
            lang = value
        elif option == '-municipality':
            municipality = value
        elif option == '-minimum':
            minimum = int(value)
        else:
            raise Exception(
                u'Bad parameters. Expected "-countrycode", "-langcode", '
                u'"-municipality", "-minimum" or pywikibot args. '
                u'Found "{}"'.format(option))

    if countrycode and lang and municipality:
        addresses = getAddresses(countrycode, lang, municipality, conn, cursor)
        printTopStreets(addresses, minimum)
    else:
        print u'Usage'

    close_database_connection(conn, cursor)
开发者ID:wikimedia,项目名称:labs-tools-heritage,代码行数:33,代码来源:top_streets.py

示例14: main

def main():
    # This temporary array is used to read the page title if one single
    # page that should be unlinked.
    pageTitle = []
    # Which namespaces should be processed?
    # default to [] which means all namespaces will be processed
    namespaces = []
    always = False

    for arg in pywikibot.handleArgs():
        if arg.startswith('-namespace:'):
            try:
                namespaces.append(int(arg[11:]))
            except ValueError:
                namespaces.append(arg[11:])
        elif arg == '-always':
            always = True
        else:
            pageTitle.append(arg)

    if pageTitle:
        page = pywikibot.Page(pywikibot.getSite(), ' '.join(pageTitle))
        bot = UnlinkBot(page, namespaces, always)
        bot.run()
    else:
        pywikibot.showHelp('unlink')
开发者ID:blueprintmrk,项目名称:pywikibot-core,代码行数:26,代码来源:unlink.py

示例15: create

def create(year):
    target = str(year)+' in the Palestinian territories'
    pg1 = pywikibot.Page(site, str(year)+' of the Palestinian territories')
    pg2 = pywikibot.Page(site, str(year)+' in Palestine')
    pg3 = pywikibot.Page(site, str(year)+' in the Palestinian National Authority'
    pg4 = pywikibot.Page(site, str(year)+' of the Palestinian National Authority')
    pg5 = pywikibot.Page(site, str(year)+' of Palestine')
    for page in [pg1, pg2, pg3, pg4, pg5]:
        if page.exists():
            continue
        print 'Creating %s' % page.title(asLink=True)
        page.put(REDIRECT % target, 'BOT EDIT: Creating redirect to [[%s]]' % target)
        talk = page.toggleTalkPage()
        if not talk.exists():
            print 'Creating %s' % talk.title(asLink=True)
            tag = '{{WikiProject Palestine|class=Redirect}}'
            summary = 'Bot: Tagging for [[Wikipedia:WikiProject Palestine]]'
            talk.put(tag, summary)
    
def main():
    year = 2000
    while year < 2012:
        create(year)
        year += 1
    create(1987)

if __name__ == "__main__":
    pywikibot.handleArgs()
    main()
开发者ID:TAP-WP,项目名称:TAP-Bot,代码行数:29,代码来源:tap_bot_one.py


注:本文中的pywikibot.handleArgs函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。