当前位置: 首页>>代码示例>>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;未经允许,请勿转载。