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


Python pywikibot.stopme函数代码示例

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


在下文中一共展示了stopme函数的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():
    fapage = pywikibot.Page(faSite, u'ویکی‌پدیا:درخواست انتقال رده')
    try:
        text = fapage.get()
        page_history = fapage.getVersionHistory()
        Last_user = page_history[0][2]
    except pywikibot.IsRedirectPage:
        fapage = fapage.getRedirectTarget()
        try:
            text = fapage.get()
            page_history = fapage.getVersionHistory()
            Last_user = page_history[0][2]
        except:
            #pywikibot.output(u"requested page didn't find!")
            pywikibot.stopme()
            sys.exit()
    except:
        #pywikibot.output(u"requested page didn't find!")
        pywikibot.stopme()
        sys.exit()
    if Last_user != u'Dexbot' and check_user(Last_user):
        fapage.put(u'{{/بالا}}', u'ربات:انتقال رده انجام شد!')
        runn(text, Last_user)
        res = {'result': 'Finished'}
        print json.dumps(res)
    else:
        res = {
            'result': 'Not done. User is not allowed, less than 3000 edits are made by last editing user'}
        print json.dumps(res)
开发者ID:reza1615,项目名称:fawikibot,代码行数:29,代码来源:dar.py

示例3: post

def post(unlock=True):
    """
    This function removes throttle file. It also removes lockfile unless
    unlock variable is set to False
    """
    if unlock or (not info["lock"]):
        try:
            os.remove(info["lockfile"])
        except OSError:
            error("unable to remove lockfile.")
    pywikibot.output("stop task at " + getTime())
    pywikibot.stopme()
开发者ID:nullzero,项目名称:wprobot,代码行数:12,代码来源:__init__.py

示例4: main

def main(*args):
    global bot
    try:
        a = pywikibot.handleArgs(*args)
        if len(a) == 1:
            raise RuntimeError('Unrecognized argument "%s"' % a[0])
        elif a:
            raise RuntimeError('Unrecognized arguments: ' +
                               " ".join(('"%s"' % arg) for arg in a))
        bot = CategoryRedirectBot()
        bot.run()
    finally:
        pywikibot.stopme()
开发者ID:iamedwardshen,项目名称:pywikibot-core,代码行数:13,代码来源:category_redirect.py

示例5: IRCcleanup

def IRCcleanup():
    while 1:
        try:
            bot = IRC_RC_Bot()
            bot.start()
        except KeyboardInterrupt:
            print "Najanona tamin'ny alalan'i CTRL+C"
            break
        except Exception:
            time.sleep(10)
            del bot
            continue

    wikipedia.stopme()
开发者ID:Webysther,项目名称:botjagwar,代码行数:14,代码来源:autocleanup.py

示例6: run

    def run(self):
        """Run the bot."""
        starttime = time()
        rc_listener = site_rc_listener(self.site, timeout=60)
        while True:
            pywikibot.output(Timestamp.now().strftime(">> %H:%M:%S: "))
            self.read_lists()
            try:
                self.markBlockedusers(self.loadBlockedUsers())
                self.contactDefendants(bootmode=self.start)
            except pywikibot.EditConflict:
                pywikibot.output("Edit conflict found, try again.")
                continue  # try again and skip waittime
            except pywikibot.PageNotSaved:
                pywikibot.output("Page not saved, try again.")
                continue  # try again and skip waittime

            # wait for new block entry
            print()
            now = time()
            pywikibot.stopme()
            for i, entry in enumerate(rc_listener):
                if i % 25 == 0:
                    print('\r', ' ' * 50, '\rWaiting for events', end='')
                if entry['type'] == 'log' and \
                   entry['log_type'] == 'block' and \
                   entry['log_action'] in ('block', 'reblock'):
                    pywikibot.output('\nFound a new blocking event '
                                     'by user "%s" for user "%s"'
                                     % (entry['user'], entry['title']))
                    break
                if entry['type'] == 'edit' and \
                   not entry['bot'] and \
                   entry['title'] == self.vmPageName:
                    pywikibot.output('\nFound a new edit by user "%s"'
                                     % entry['user'])
                    break
                if not entry['bot']:
                    print('.', end='')
            print('\n')

            self.optOutListAge += time() - now

            # read older entries again after ~4 minutes
            if time() - starttime > 250:
                starttime = time()
                self.reset_timestamp()
            self.start = False
            self.total = 10
开发者ID:edgarskos,项目名称:pywikibot-bots-xqbot,代码行数:49,代码来源:vandalism.py

示例7: main

def main(*args):
    try:
        gen = None
        genFactory = GeneratorFactory()
        for arg in pywikibot.handleArgs(*args):
            genFactory.handleArg(arg)
        gen = genFactory.getCombinedGenerator()
        if gen:
            for page in gen:
                pywikibot.stdout(page.title())
        else:
            pywikibot.showHelp()
    except Exception:
        pywikibot.error("Fatal error", exc_info=True)
    finally:
        pywikibot.stopme()
开发者ID:azatoth,项目名称:pywikipedia,代码行数:16,代码来源:pagegenerators.py

示例8: main

def main():
    wikipedia.stopme()
    (wikipedia.config).put_throttle = int(1)
    timeshift=3
    bot = Wikilister()

    while(1):
        t = list(time.gmtime())
        cond = (not (t[3]+timeshift)%6) and (t[4]==0)
        if cond:
            bot.run('Wikibolana','wiktionary')
            bot.run('Wikipedia','wikipedia')
            time.sleep(120)
        else:
            print "Fanavaozana isaky ny adin'ny 6"
            print "Miandry ny fotoana tokony hamaozana ny pejy (ora %2d:%2d) (GMT+%d)"%((t[3]+timeshift),t[4],(timeshift))
            time.sleep(30)
开发者ID:Webysther,项目名称:botjagwar,代码行数:17,代码来源:list_wikis.py

示例9: main

def main():
    """
    Run some tests.
    """

    from suggestbot import SuggestBot

    mybot = SuggestBot()
    myhandler = WikiProjectHandler(mybot)

    logging.info(u"instantiated WikiProjectHandler and SuggestBot objects, testing request handling...")

    try:
        myhandler.process_requests()
    finally:
        pywikibot.stopme()
        
    # OK, done...
    return
开发者ID:nettrom,项目名称:suggestbot,代码行数:19,代码来源:wikiprojects.py

示例10: main

def main():
    global CD
    output(u'Running ' + __version__)
    CD = CommonsDelinker()
    output(u'This bot runs from: ' + str(CD.site))

    re._MAXCACHE = 4

    args = pywikibot.handle_args()
    if '-since' in args:
        # NOTE: Untested
        ts_format = '%Y-%m-%d %H:%M:%S'
        try:
            since = time.strptime(
                args[args.index('-since') + 1],
                ts_format)
        except ValueError:
            if args[args.index('-since') + 1][0] == '[' and \
                    len(args) != args.index('-since') + 2:
                since = time.strptime('%s %s' % \
                    args[args.index('-since') + 1],
                    '[%s]' % ts_format)
            else:
                raise ValueError('Incorrect time format!')
        output(u'Reading deletion log since [%s]' %\
            time.strftime(ts_format, since))
        CD.last_check = time.mktime(since)

    try:
        try:
            CD.start()
        except Exception, e:
            if type(e) not in (SystemExit, KeyboardInterrupt):
                output('An exception occured in the main thread!', False)
                traceback.print_exc(file = sys.stderr)
                threadpool.terminate()
    finally:
        output(u'Stopping CommonsDelinker')
        pywikibot.stopme()
        # Flush the standard streams
        sys.stdout.flush()
        sys.stderr.flush()
开发者ID:edgarskos,项目名称:pywikibot-bots-CommonsDelinker,代码行数:42,代码来源:delinker.py

示例11: main

def main():
    global R

    import sys, traceback
    pywikibot.handleArgs()
    output(u'Running ' + __version__)

    try:
        try:
            # FIXME: Add support for single-process replacer.
            R = Replacer()
            output(u'This bot runs from: ' + str(R.site))
            R.start()
        except (SystemExit, KeyboardInterrupt):
            raise
        except Exception, e:
            output('A critical error has occured! Aborting!')
            traceback.print_exc(file = sys.stderr)
    finally:
        output('Exitting replacer')
        pywikibot.stopme()
开发者ID:edgarskos,项目名称:pywikibot-bots-CommonsDelinker,代码行数:21,代码来源:image_replacer.py

示例12: main

def main():
    """
    Process command line arguments and invoke bot.

    If args is an empty list, sys.argv is used.

    @param args: command line arguments
    @type args: list of unicode
    """
    options = {}
    for arg in pywikibot.handle_args():
        options[arg[1:]] = True

    bot = AFDNoticeBot(**options)
    while True:
        bot.run()
        pywikibot.output('Waiting 300 seconds...\n')
        pywikibot.stopme()
        try:
            time.sleep(300)
        except KeyboardInterrupt:
            bot.exit()
            break
开发者ID:wikimedia,项目名称:pywikibot-bots-xqbot,代码行数:23,代码来源:afd_notice.py

示例13: main

def main():
    summary_commandline, gen, template = None, None, None
    namespaces, PageTitles, exceptions = [], [], []
    encat, newcatfile = "", ""
    autoText, autoTitle = False, False
    recentcat, newcat = False, False
    genFactory = pagegenerators.GeneratorFactory()
    for arg in pywikibot.handleArgs():
        if arg == "-autotitle":
            autoTitle = True
        elif arg == "-autotext":
            autoText = True
        elif arg.startswith("-page"):
            if len(arg) == 5:
                PageTitles.append(pywikibot.input(u"Which page do you want to chage?"))
            else:
                PageTitles.append(arg[6:])
            break
        elif arg.startswith("-except:"):
            exceptions.append(arg[8:])
        elif arg.startswith("-template:"):
            template = arg[10:]
        elif arg.startswith("-facat:"):
            facat = arg.replace(u"Category:", u"").replace(u"category:", u"").replace(u"رده:", u"")
            encat = (
                englishdictionry(u"رده:" + facat[7:], fa_site, en_site)
                .replace(u"Category:", u"")
                .replace(u"category:", u"")
            )
            break
        elif arg.startswith("-encat:"):
            encat = arg[7:].replace(u"Category:", u"").replace(u"category:", u"").replace(u"رده:", u"")
            break
        elif arg.startswith("-newcatfile:"):
            newcatfile = arg[12:]
            break
        elif arg.startswith("-recentcat"):
            arg = arg.replace(":", "")
            if len(arg) == 10:
                genfa = pagegenerators.RecentchangesPageGenerator()
            else:
                genfa = pagegenerators.RecentchangesPageGenerator(number=int(arg[10:]))
            genfa = pagegenerators.DuplicateFilterPageGenerator(genfa)
            genfa = pagegenerators.NamespaceFilterPageGenerator(genfa, [14])
            preloadingGen = pagegenerators.PreloadingGenerator(genfa, 60)
            recentcat = True
            break
        elif arg.startswith("-newcat"):
            arg = arg.replace(":", "")
            if len(arg) == 7:
                genfa = pagegenerators.NewpagesPageGenerator(step=100, namespaces=14)
            else:
                genfa = pagegenerators.NewpagesPageGenerator(step=int(arg[7:]), namespaces=14)
            preloadingGen = pagegenerators.PreloadingGenerator(genfa, 60)
            newcat = True
            break
        elif arg.startswith("-namespace:"):
            namespaces.append(int(arg[11:]))
        elif arg.startswith("-summary:"):
            pywikibot.setAction(arg[9:])
            summary_commandline = True
        else:
            generator = genFactory.handleArg(arg)
            if generator:
                gen = genFactory.getCombinedGenerator(gen)
    if encat != "":
        encatfalist, encatlists = encatlist(encat)
        if encatlists:
            for encat in encatlists:
                encat = englishdictionry(encat, en_site, fa_site)
                if encat:
                    run([encat])
        if encatfalist is not False:
            run(encatfalist)
    if PageTitles:
        pages = [pywikibot.Page(fa_site, PageTitle) for PageTitle in PageTitles]
        gen = iter(pages)
    if recentcat:
        for workpage in preloadingGen:
            workpage = workpage.title()
            cat = pywikibot.Category(fa_site, workpage)
            gent = pagegenerators.CategorizedPageGenerator(cat)
            run(gent)
        pywikibot.stopme()
        sys.exit()
    if newcat:
        for workpage in preloadingGen:
            workpage = workpage.title()
            workpage = englishdictionry(workpage, fa_site, en_site)
            if workpage is not False:
                encatfalist, encatlists = encatlist(workpage)
                if encatlists:
                    for encat in encatlists:
                        encat = englishdictionry(encat, en_site, fa_site)
                        if encat:
                            run([encat])
                if encatfalist is not False:
                    run(encatfalist)
        pywikibot.stopme()
        sys.exit()
#.........这里部分代码省略.........
开发者ID:PersianWikipedia,项目名称:fawikibot,代码行数:101,代码来源:rade.py

示例14: mpanao

                else:
                    for n in nombre:
                        yield [u'%s%s%s%s%s' %(t, verb[:-2].lower(), desinence, n, m),
                           u"''%s %s ny bika %s %s ny matoanteny [[%s]].''" %(desinences[desinence], nombre[n], temps[t], modes[m], verb),
                           u"Avy amin'ny tovona <i>%s</i>- mamaritra ny fitaona %s, ny fototeny [[%s]] ; ny tovana -<i>[[%s]]</i> izay mamaritra ny mpanao (%s) ; " %(t, temps[t], verb[:-2], desinence, desinences[desinence].lower()) +
                           " ary ny tovana -<i>%s</i> mamaritra ny %s " %(n, nombre[n])]
            

def genbatch():
    pages = file('batch/voverbs.txt','r').readlines()
    out = open("data/vowords.txt","w")
    n = 0
    for mot in pages:
        if len(mot) < 2: continue
        mot = mot.decode('utf8')
        for i in get_desinences(mot):
            outstr = i[0]+u"\n"
            out.write(outstr.encode('utf8'))
    print n
    out.close()

try:
    main()
    #genbatch()
    #evaluate()
except KeyboardInterrupt:
    wikipedia.stopme()
finally:
    wikipedia.stopme()

开发者ID:Webysther,项目名称:botjagwar,代码行数:29,代码来源:voverb.py

示例15: int

            else:
                if page.namespace():
                    continue
                found = 1

            if not found:
                if dluga:
                    table += '\n|-\n| [[{0}]] || {1}'.format(tmp[0], int(tmp[1]))
                else:
                    table += '\n|-\n| [[{0}]] || [{{{{fullurl:Specjalna:Linkujące|limit=500&from=0&target={1}}}}} {2}]'.format(tmp[0], tmp[0].replace(' ', '_'), int(tmp[1]))
                i += 1

    table += '\n|-\n|}'

    with open('{0}output/frequencyProcessedTable.txt'.format(config.path['scripts']), encoding='utf-8', mode='w') as g:
        g.write(table)

    if dluga:
        outputPage = pwb.Page(site, 'Wikipedysta:AlkamidBot/listy/Najbardziej_potrzebne_-_długa_lista')
    else:
        outputPage = pwb.Page(site, 'Wikipedysta:AlkamidBot/listy/Najbardziej_potrzebne')

    outputPage.text = table
    outputPage.save(summary='aktualizacja')

if __name__ == '__main__':
    try:
        frequencyListUpdate()
    finally:
        pwb.stopme()
开发者ID:alkamid,项目名称:wiktionary,代码行数:30,代码来源:frequencyListUpdate.py


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