當前位置: 首頁>>代碼示例>>Python>>正文


Python pywikibot.warning方法代碼示例

本文整理匯總了Python中pywikibot.warning方法的典型用法代碼示例。如果您正苦於以下問題:Python pywikibot.warning方法的具體用法?Python pywikibot.warning怎麽用?Python pywikibot.warning使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pywikibot的用法示例。


在下文中一共展示了pywikibot.warning方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: overwrite

# 需要導入模塊: import pywikibot [as 別名]
# 或者: from pywikibot import warning [as 別名]
def overwrite(filepage, msg, res, path):
    filepage._file_revisions.clear()

    if not filepage.get_file_history():
        pywikibot.warning("Page doesn't exist, skipping upload.")
        return

    with tempfile.NamedTemporaryFile() as tmp:
        with open(path, 'rb') as old:
            shutil.copyfileobj(old, tmp)

        tmp.truncate(res[0]['pos'])
        retry_apierror(
            lambda:
            filepage.upload(tmp.name,
                            comment=MESSAGE_PREFIX+msg,
                            ignore_warnings=True)
        ) 
開發者ID:toolforge,項目名稱:embeddeddata,代碼行數:20,代碼來源:worker.py

示例2: delete

# 需要導入模塊: import pywikibot [as 別名]
# 或者: from pywikibot import warning [as 別名]
def delete(filepage, msg):
    for i in range(8):
        filepage._file_revisions.clear()
        filepage.clear_cache()

        try:
            hist = filepage.get_file_history()
        except Exception:
            hist = None

        if not filepage.exists() and not hist:
            break
        else:
            if i:
                pywikibot.warning(
                    'File exist still before deletion on attempt %d' % i)
            pywikibot.output('Executing delete on %s' % filepage)

            retry_apierror(
                lambda:
                filepage.delete(MESSAGE_PREFIX+msg, prompt=False)
            )
    else:
        pywikibot.warning('FIXME: Deletion attempt exhausted') 
開發者ID:toolforge,項目名稱:embeddeddata,代碼行數:26,代碼來源:worker.py

示例3: loop_over_candidates

# 需要導入模塊: import pywikibot [as 別名]
# 或者: from pywikibot import warning [as 別名]
def loop_over_candidates(parent_cat, church_dict, parent_ending, depth=0):
    """Determine if a category is a candidate or if we should go deeper."""
    if depth > 3:
        # Don't go too deep but make sure it'snot completely discarded
        pwb.warning('Too deep: {}'.format(
            parent_cat.title(withNamespace=False)))
        add_if_likely_church(parent_cat, church_dict)
        return
    for church_cat in parent_cat.subcategories():
        name = church_cat.title(withNamespace=False)
        if (has_subcats(church_cat) and
                (name.endswith(parent_ending) or
                 name.startswith('Churches in '))):
            loop_over_candidates(
                church_cat, church_dict, parent_ending, depth=depth+1)
        else:
            add_if_likely_church(church_cat, church_dict) 
開發者ID:lokal-profil,項目名稱:KMB-import,代碼行數:19,代碼來源:load_church_cats.py

示例4: retry_apierror

# 需要導入模塊: import pywikibot [as 別名]
# 或者: from pywikibot import warning [as 別名]
def retry_apierror(f):
    for i in range(8):
        try:
            f()
        except APIError:
            pywikibot.warning(
                'Failed API request on attempt %d' % i)
        else:
            break
    else:
        raise 
開發者ID:toolforge,項目名稱:embeddeddata,代碼行數:13,代碼來源:worker.py

示例5: protect

# 需要導入模塊: import pywikibot [as 別名]
# 或者: from pywikibot import warning [as 別名]
def protect(filepage, msg):
    # Make sure this is not executed on a page that is already protected.
    # For newly uploaded files this is fine.
    protectmsg = (
        '[[Commons:Protection policy|Protection against re-creation]]: ' +
        MESSAGE_PREFIX + msg)
    ev = threading.Event()

    def _protect(typ):
        try:
            filepage.protect(
                protections={typ: 'autoconfirmed'},
                expiry='1 minute',
                reason=protectmsg,
                prompt=False
            )
        except (APIError, pywikibot.Error):
            pass
        else:
            ev.set()

    upload_thread = threading.Thread(target=lambda: _protect('upload'))
    create_thread = threading.Thread(target=lambda: _protect('create'))
    upload_thread.start()
    create_thread.start()
    upload_thread.join()
    create_thread.join()

    if not ev.is_set():
        pywikibot.warning('Protection of %s failed.' % filepage) 
開發者ID:toolforge,項目名稱:embeddeddata,代碼行數:32,代碼來源:worker.py

示例6: add_speedy

# 需要導入模塊: import pywikibot [as 別名]
# 或者: from pywikibot import warning [as 別名]
def add_speedy(filepage, msg):
    filepage.clear_cache()

    if not filepage.exists():
        pywikibot.warning("Page doesn't exist, skipping save.")
        return

    # Make sure no edit conflicts happen here
    retry_apierror(
        lambda:
        filepage.save(prependtext='{{embedded data|suspect=1|1=%s}}\n' % msg,
                      summary='Bot: Adding {{[[Template:Embedded data|'
                      'embedded data]]}} to this embedded data suspect.')
    ) 
開發者ID:toolforge,項目名稱:embeddeddata,代碼行數:16,代碼來源:worker.py

示例7: main

# 需要導入模塊: import pywikibot [as 別名]
# 或者: from pywikibot import warning [as 別名]
def main(*args):
    generator = None
    local_args = pywikibot.handle_args(args)
    site = pywikibot.Site()
    if str(site) != "commons:commons":
        pywikibot.warning("The script has not been tested on sites other that "
                          "commons:commons.")

    gen_factory = pagegenerators.GeneratorFactory(site)
    for local_arg in local_args:
        if gen_factory.handleArg(local_arg):
            continue
        arg, sep, value = local_arg.partition(':')
        if arg in ('-showcats',):
            options[arg[1:]] = True
        else:
            raise ValueError('Unknown argument: ' + local_arg)

    generator = gen_factory.getCombinedGenerator(gen=generator)
    if not generator:
        pywikibot.bot.suggest_help(missing_generator=True)
    else:
        pregenerator = pagegenerators.PreloadingGenerator(generator)
        for i, page in enumerate(pregenerator):
            if page.exists():
                log = handle_page(page)
                pywikibot.output('\n'.join(log))
                pywikibot.output("") 
開發者ID:pywikibot-catfiles,項目名稱:file-metadata,代碼行數:30,代碼來源:simple_bot.py

示例8: summary_hook

# 需要導入模塊: import pywikibot [as 別名]
# 或者: from pywikibot import warning [as 別名]
def summary_hook(self, match, replaced):
        def underscores(string):
            if string.startswith(' '):
                string = '_' + string[1:]
            if string.endswith(' '):
                string = string[:-1] + '_'
            return string

        new = old = match.group()
        if self.needsDecision():
            options = [('keep', 'k')]
            replacements = []
            for i, repl in enumerate(self.replacements, start=1):
                replacement = match.expand(repl)
                replacements.append(replacement)
                options.append(
                    ('%s %s' % (i, underscores(replacement)), str(i))
                )
            text = match.string
            pre = text[max(0, match.start() - 30):match.start()].rpartition('\n')[2]
            post = text[match.end():match.end() + 30].partition('\n')[0]
            pywikibot.output(color_format('{0}{lightred}{1}{default}{2}',
                                          pre, old, post))
            choice = pywikibot.input_choice('Choose the best replacement',
                                            options, automatic_quit=False,
                                            default='k')
            if choice != 'k':
                new = replacements[int(choice) - 1]
        else:
            new = match.expand(self.replacements[0])
            if old == new:
                pywikibot.warning('No replacement done in string "%s"' % old)

        if old != new:
            fragment = ' ? '.join(underscores(re.sub('\n', r'\\n', i))
                                  for i in (old, new))
            if fragment.lower() not in map(methodcaller('lower'), replaced):
                replaced.append(fragment)
        return new 
開發者ID:matejsuchanek,項目名稱:pywikibot-scripts,代碼行數:41,代碼來源:typoloader.py

示例9: apply

# 需要導入模塊: import pywikibot [as 別名]
# 或者: from pywikibot import warning [as 別名]
def apply(self, text, replaced=[]):
        hook = lambda match: self.summary_hook(match, replaced)
        start = time.clock()
        text = textlib.replaceExcept(
            text, self.find, hook, self.exceptions, site=self.site)
        finish = time.clock()
        delta = finish - start
        self.longest = max(delta, self.longest)
        if delta > 5:
            pywikibot.warning('Slow typo rule "%s" (%s)' % (
                self.find.pattern, delta))
        return text 
開發者ID:matejsuchanek,項目名稱:pywikibot-scripts,代碼行數:14,代碼來源:typoloader.py

示例10: loadTypos

# 需要導入模塊: import pywikibot [as 別名]
# 或者: from pywikibot import warning [as 別名]
def loadTypos(self):
        pywikibot.output('Loading typo rules')
        self.typoRules = []

        if self.typos_page_name is None:
            self.typos_page_name = 'Wikipedie:WPCleaner/Typo'
        typos_page = pywikibot.Page(self.site, self.typos_page_name)
        if not typos_page.exists():
            # todo: feedback
            return

        content = typos_page.get()
        load_all = self.load_all is True
        for template, fielddict in textlib.extract_templates_and_params(
            content, remove_disabled_parts=False, strip=False):
            if template.lower() == 'typo':
                try:
                    rule = TypoRule.newFromParameters(fielddict, self.site)
                except IncompleteTypoRuleException as exc:
                    pywikibot.warning(exc.message) # pwb.exception?
                except InvalidExpressionException as exc:
                    if 'fixed-width' not in exc.message:
                        pywikibot.warning('Invalid %s %s: %s' % (
                            exc.aspect, fielddict['1'], exc.message))
                else:
                    rule.id = self.top_id
                    self.top_id += 1
                    if load_all or not rule.needsDecision():
                        self.typoRules.append(rule)

        pywikibot.output('%s typo rules loaded' % len(self.typoRules))
        return self.typoRules 
開發者ID:matejsuchanek,項目名稱:pywikibot-scripts,代碼行數:34,代碼來源:typoloader.py

示例11: filterProperty

# 需要導入模塊: import pywikibot [as 別名]
# 或者: from pywikibot import warning [as 別名]
def filterProperty(self, prop_page):
        if prop_page.type == 'external-id':
            return False

        prop_page.get()
        if 'P31' not in prop_page.claims.keys():
            pywikibot.warning('%s is not classified' % prop_page.getID())
            return False

        for claim in prop_page.claims['P31']:
            if claim.target_equals(self.good_item):
                return True

        return False 
開發者ID:matejsuchanek,項目名稱:pywikibot-scripts,代碼行數:16,代碼來源:fix_qualifiers.py

示例12: treat_page

# 需要導入模塊: import pywikibot [as 別名]
# 或者: from pywikibot import warning [as 別名]
def treat_page(self):
        page = self.current_page
        text = page.text
        done_replacements = []
        quickly = self.getOption('quick') is True
        start = time.clock()
        if self.own_generator:
            text = self.currentrule.apply(page.text, done_replacements)
            if page.text == text:
                if quickly:
                    pywikibot.output('Typo not found, not fixing another typos '
                                     'in quick mode')
                    return
            else:
                self.replaced += 1

        for rule in self.typoRules:
            if self.own_generator and rule == self.currentrule: # __eq__
                continue
            if rule.matches(page.title()):
                continue
            if quickly and rule.needsDecision():
                continue

            text = rule.apply(text, done_replacements)
            stop = time.clock()
            if quickly and stop - start > 15:
                pywikibot.warning('Other typos exceeded 15s, skipping')
                break

        self.put_current(
            text, summary='oprava p?eklep?: %s' % ', '.join(done_replacements)) 
開發者ID:matejsuchanek,項目名稱:pywikibot-scripts,代碼行數:34,代碼來源:typos.py

示例13: sortkey

# 需要導入模塊: import pywikibot [as 別名]
# 或者: from pywikibot import warning [as 別名]
def sortkey(self, sect):
        if sect['name'] == self.root_header:
            return -1
        if sect['name'] in self.headers_in_order:
            return self.headers_in_order.index(sect['name'])
        pywikibot.warning('Found unknown header: "%s"' % sect['name'])
        return len(self.headers_in_order) 
開發者ID:matejsuchanek,項目名稱:pywikibot-scripts,代碼行數:9,代碼來源:custome_fixes.py

示例14: deduplicate

# 需要導入模塊: import pywikibot [as 別名]
# 或者: from pywikibot import warning [as 別名]
def deduplicate(self, params):
        keys = [i for i, j in params]
        duplicates = set(filter(lambda x: keys.count(x) > 1, keys))
        if duplicates:
            pywikibot.warning('Duplicate arguments %s' % duplicates)
            for dupe in duplicates:
                values = list(filter(lambda x: x[0] == dupe, params))
                while '' in values:
                    params.remove((dupe, ''))
                    values.remove('')
                #while len(set(values)) < len(values): todo 
開發者ID:matejsuchanek,項目名稱:pywikibot-scripts,代碼行數:13,代碼來源:migrate_infobox.py

示例15: detect

# 需要導入模塊: import pywikibot [as 別名]
# 或者: from pywikibot import warning [as 別名]
def detect(f):
    with UpdatingFileProxy(open(f, 'rb')) as f:
        ret = []
        for detector, magic in detectors.items():
            f.unset_pos()
            f.seek(0, os.SEEK_SET)

            # search for magic
            for startpos in list(find_startpos(f, magic)):
                # print detector, magic, startpos
                f.seek(startpos)
                try:
                    out = detector(f)
                except (FileCorrupted, ValueError, TypeError, struct.error):
                    traceback.print_exc()
                    out = True

                endpos = f.last_good_pos
                if not out or endpos is None:
                    pywikibot.warning('Really corrupted file?!')
                    continue

                size = endpos - startpos
                if out is not Ellipsis and size < 128:
                    pywikibot.warning('Very small file?!')
                    continue

                with tempfile.NamedTemporaryFile() as tmp:
                    f.seek(startpos)
                    while True:
                        read = f.read(CHUNK_SIZE)
                        if not read:
                            break
                        tmp.write(read)

                    tmp.flush()
                    mime = filetype(tmp.name), filetype(tmp.name, False)

                ret.append({
                    'pos': startpos,
                    'len': size,
                    'mime': mime
                })

        return ret 
開發者ID:toolforge,項目名稱:embeddeddata,代碼行數:47,代碼來源:__init__.py


注:本文中的pywikibot.warning方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。