• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python tools.issue_deprecation_warning函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: main

def main(*args):
    """
    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 = {}
    local_args = pywikibot.handle_args(args)

    issue_deprecation_warning(
        'featured.py script', 'Wikibase Client extension',
        0, UserWarning)

    for arg in local_args:
        if arg.startswith('-fromlang:'):
            options[arg[1:9]] = arg[10:].split(",")
        elif arg.startswith('-after:'):
            options['afterpage'] = arg[7:]
        elif arg.startswith('-nocache:'):
            options[arg[1:8]] = arg[9:].split(",")
        else:
            options[arg[1:].lower()] = True

    bot = FeaturedBot(**options)
    bot.run()
开发者ID:magul,项目名称:pywikibot-core,代码行数:28,代码来源:featured.py


示例2: replace_plural

    def replace_plural(match):
        selector = match.group(1)
        variants = match.group(2)
        num = parameters[selector]
        if not isinstance(num, int):
            issue_deprecation_warning("type {0} for value {1} ({2})".format(type(num), selector, num), "an int", 1)
            num = int(num)

        plural_entries = []
        specific_entries = {}
        for number, plural in re.findall(r"\|?(?: *(\d+) *= *)?([^|]+)", variants):
            if number:
                specific_entries[int(number)] = plural
            else:
                assert not specific_entries, 'generic entries defined after specific in "{0}"'.format(variants)
                plural_entries += [plural]

        if num in specific_entries:
            return specific_entries[num]

        index = plural_value(num)
        if rule["nplurals"] == 1:
            assert index == 0

        if index >= len(plural_entries):
            raise IndexError(
                'requested plural {0} for {1} but only {2} ("{3}") '
                "provided".format(index, selector, len(plural_entries), '", "'.join(plural_entries))
            )
        return plural_entries[index]
开发者ID:KaiCode2,项目名称:pywikibot-core,代码行数:30,代码来源:i18n.py


示例3: output

def output(text, decoder=None, newline=True, toStdout=False, **kwargs):
    r"""Output a message to the user via the userinterface.

    Works like print, but uses the encoding used by the user's console
    (console_encoding in the configuration file) instead of ASCII.

    If decoder is None, text should be a unicode string. Otherwise it
    should be encoded in the given encoding.

    If newline is True, a line feed will be added after printing the text.

    If toStdout is True, the text will be sent to standard output,
    so that it can be piped to another process. All other text will
    be sent to stderr. See: https://en.wikipedia.org/wiki/Pipeline_%28Unix%29

    text can contain special sequences to create colored output. These
    consist of the escape character \03 and the color name in curly braces,
    e. g. \03{lightpurple}. \03{default} resets the color. By using the
    color_format method from pywikibot.tools.formatter, the escape character
    may be omitted.

    Other keyword arguments are passed unchanged to the logger; so far, the
    only argument that is useful is "exc_info=True", which causes the
    log message to include an exception traceback.
    """
    if toStdout:  # maintained for backwards-compatibity only
        from pywikibot.tools import issue_deprecation_warning  # noqa
        issue_deprecation_warning('"toStdout" parameter',
                                  'pywikibot.stdout()', 2)
        logoutput(text, decoder, newline, STDOUT, **kwargs)
    else:
        logoutput(text, decoder, newline, INFO, **kwargs)
开发者ID:runt18,项目名称:pywikibot-core,代码行数:32,代码来源:logging.py


示例4: main

def main(*args):
    """
    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
    """
    # Process global arguments to determine desired site
    local_args = pywikibot.handle_args(args)

    # This factory is responsible for processing command line arguments
    # that are also used by other scripts and that determine on which pages
    # to work on.
    genFactory = pagegenerators.GeneratorFactory()

    # Parse command line arguments
    for arg in local_args:
        if arg == '-dry':
            issue_deprecation_warning('-dry option', '-simulate', 1)
            pywikibot.config.simulate = True
        else:
            genFactory.handleArg(arg)

    gen = genFactory.getCombinedGenerator()
    if gen:
        # The preloading generator is responsible for downloading multiple
        # pages from the wiki simultaneously.
        gen = pagegenerators.PreloadingGenerator(gen)
        bot = BasicBot(gen)
        bot.run()
    else:
        pywikibot.showHelp()
开发者ID:emijrp,项目名称:pywikibot-core,代码行数:34,代码来源:basic.py


示例5: main

def main(*args):
    """
    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
    """
    generator = None

    local_args = pywikibot.handle_args(args)

    site = pywikibot.Site()

    if site.code != 'commons' or site.family.name != 'commons':
        pywikibot.warning('This script is primarily written for Wikimedia '
                          'Commons, but has been invoked with site {0}. It '
                          'might work for other sites but there is no '
                          'guarantee that it does the right thing.'.format(site))
        choice = pywikibot.input_choice(
            'How do you want to continue?',
            (('Continue using {0}'.format(site), 'c'),
             ('Switch to Wikimedia Commons', 's'),
             ('Quit', 'q')),
            automatic_quit=False)
        if choice == 's':
            site = pywikibot.Site('commons', 'commons')
        elif choice == 'q':
            return False

    genFactory = pagegenerators.GeneratorFactory(site)

    for arg in local_args:
        if arg.startswith('-yesterday'):
            generator = uploadedYesterday(site)
            issue_deprecation_warning(
                'The usage of "-yesterday"',
                '-logevents:"upload,,YYYYMMDD,YYYYMMDD"',
                2, ArgumentDeprecationWarning)
        elif arg.startswith('-recentchanges'):
            generator = recentChanges(site=site, delay=120)
        else:
            genFactory.handleArg(arg)

    generator = genFactory.getCombinedGenerator(gen=generator)
    if not generator:
        pywikibot.bot.suggest_help(missing_generator=True)
        return False
    else:
        pregenerator = pagegenerators.PreloadingGenerator(generator)
        site.login()
        for page in pregenerator:
            pywikibot.output(page.title())
            if page.exists() and (page.namespace() == 6) \
                    and (not page.isRedirectPage()):
                if isUncat(page):
                    addUncat(page)
        return True
开发者ID:Tillsa,项目名称:pywikibot_test_wikidata,代码行数:59,代码来源:imageuncat.py


示例6: request

def request(site=None, uri=None, method='GET', params=None, body=None,
            headers=None, data=None, **kwargs):
    """
    Request to Site with default error handling and response decoding.

    See L{requests.Session.request} for additional parameters.

    If the site argument is provided, the uri is a relative uri from
    and including the document root '/'.

    If the site argument is None, the uri must be absolute.

    @param site: The Site to connect to
    @type site: L{pywikibot.site.BaseSite}
    @param uri: the URI to retrieve
    @type uri: str
    @param charset: Either a valid charset (usable for str.decode()) or None
        to automatically chose the charset from the returned header (defaults
        to latin-1)
    @type charset: CodecInfo, str, None
    @return: The received data
    @rtype: a unicode string
    """
    # body and data parameters both map to the data parameter of
    # requests.Session.request.
    if data:
        body = data

    assert(site or uri)
    if not site:
        # +1 because of @deprecate_arg
        issue_deprecation_warning(
            'Invoking http.request without argument site', 'http.fetch()', 3)
        r = fetch(uri, method, params, body, headers, **kwargs)
        return r.content

    baseuri = site.base_url(uri)

    kwargs.setdefault("disable_ssl_certificate_validation",
                      site.ignore_certificate_error())

    if not headers:
        headers = {}
        format_string = None
    else:
        format_string = headers.get('user-agent', None)

    headers['user-agent'] = user_agent(site, format_string)

    r = fetch(baseuri, method, params, body, headers, **kwargs)
    return r.content
开发者ID:hasteur,项目名称:g13bot_tools_new,代码行数:51,代码来源:http.py


示例7: __init__

    def __init__(self, generator, dry=False, **kwargs):
        """
        Constructor.

        @param generator: the page generator that determines on which pages
            to work
        @type generator: generator
        @param dry: if True, doesn't do any real changes, but only shows
            what would have been changed
        @type dry: bool
        """
        if dry:
            issue_deprecation_warning('dry argument', 'pywikibot.config.simulate', 1)
            pywikibot.config.simulate = True
        super(BasicBot, self).__init__(site=True, **kwargs)
        self.generator = generator

        # Set the edit summary message
        self.summary = i18n.twtranslate(self.site, 'basic-changing')
开发者ID:KaiCode2,项目名称:pywikibot-core,代码行数:19,代码来源:basic.py


示例8: _handle_dry_param

    def _handle_dry_param(self, **kwargs):
        """
        Read the dry parameter and set the simulate variable instead.

        This is a private method. It prints a deprecation warning for old
        -dry paramter and sets the global simulate variable and informs
        the user about this setting.

        The constuctor of the super class ignores it because it is not
        part of self.availableOptions.

        @note: You should ommit this method in your own application.

        @keyword dry: deprecated option to prevent changes on live wiki.
            Use -simulate instead.
        @type dry: bool
        """
        if "dry" in kwargs:
            issue_deprecation_warning("dry argument", "pywikibot.config.simulate", 1)
            # use simulate variable instead
            pywikibot.config.simulate = True
            pywikibot.output("config.simulate was set to True")
开发者ID:h4ck3rm1k3,项目名称:pywikibot-core,代码行数:22,代码来源:basic.py


示例9: checkstr

def checkstr(string):
    """
    Return the key and duration extracted from the string.

    @param string: a string defining a time period:
        300s - 300 seconds
        36h - 36 hours
        7d - 7 days
        2w - 2 weeks (14 days)
        1y - 1 year
    @type string: str
    @return: key and duration extracted form the string
    @rtype: (str, str)
    """
    key = string[-1]
    if string.isdigit():
        key = 's'
        duration = string
        issue_deprecation_warning('Time period without qualifier',
                                  string + key, 1, UserWarning)
    else:
        duration = string[:-1]
    return key, duration
开发者ID:hasteur,项目名称:g13bot_tools_new,代码行数:23,代码来源:archivebot.py


示例10: replace_plural

    def replace_plural(match):
        selector = match.group(1)
        variants = match.group(2)
        num = parameters[selector]
        if not isinstance(num, int):
            issue_deprecation_warning(
                'type {0} for value {1} ({2})'.format(type(num), selector, num),
                'an int', 1)
            num = int(num)

        plural_entries = []
        specific_entries = {}
        # A plural entry can not start at the end of the variants list,
        # and must end with | or the end of the variants list.
        for number, plural in re.findall(r'(?!$)(?: *(\d+) *= *)?(.*?)(?:\||$)',
                                         variants):
            if number:
                specific_entries[int(number)] = plural
            else:
                assert not specific_entries, \
                    'generic entries defined after specific in "{0}"'.format(variants)
                plural_entries += [plural]

        if num in specific_entries:
            return specific_entries[num]

        index = plural_value(num)
        if rule['nplurals'] == 1:
            assert index == 0

        if index >= len(plural_entries):
            raise IndexError(
                'requested plural {0} for {1} but only {2} ("{3}") '
                'provided'.format(
                    index, selector, len(plural_entries),
                    '", "'.join(plural_entries)))
        return plural_entries[index]
开发者ID:hasteur,项目名称:g13bot_tools_new,代码行数:37,代码来源:i18n.py


示例11: main


#.........这里部分代码省略.........
        elif arg.startswith("-requiretitle:"):
            exceptions["require-title"].append(arg[14:])
        elif arg.startswith("-excepttext:"):
            exceptions["text-contains"].append(arg[12:])
        elif arg.startswith("-exceptinside:"):
            exceptions["inside"].append(arg[14:])
        elif arg.startswith("-exceptinsidetag:"):
            exceptions["inside-tags"].append(arg[17:])
        elif arg.startswith("-fix:"):
            fixes_set += [arg[5:]]
        elif arg.startswith("-sleep:"):
            sleep = float(arg[7:])
        elif arg == "-always":
            acceptall = True
        elif arg == "-recursive":
            recursive = True
        elif arg == "-nocase":
            caseInsensitive = True
        elif arg == "-dotall":
            dotall = True
        elif arg == "-multiline":
            multiline = True
        elif arg.startswith("-addcat:"):
            add_cat = arg[8:]
        elif arg.startswith("-summary:"):
            edit_summary = arg[9:]
        elif arg.startswith("-automaticsummary"):
            edit_summary = True
        elif arg.startswith("-allowoverlap"):
            allowoverlap = True
        elif arg.startswith("-manualinput"):
            manual_input = True
        elif arg.startswith("-replacementfile"):
            issue_deprecation_warning("-replacementfile", "-pairsfile", 2, ArgumentDeprecationWarning)
        elif arg.startswith("-pairsfile"):
            if len(commandline_replacements) % 2:
                replacement_file_arg_misplaced = True

            if arg == "-pairsfile":
                replacement_file = pywikibot.input("Please enter the filename to read replacements from:")
            else:
                replacement_file = arg[len("-pairsfile:") :]
        else:
            commandline_replacements.append(arg)

    site = pywikibot.Site()

    if len(commandline_replacements) % 2:
        pywikibot.error("Incomplete command line pattern replacement pair.")
        return False

    if replacement_file_arg_misplaced:
        pywikibot.error("-pairsfile used between a pattern replacement pair.")
        return False

    if replacement_file:
        try:
            with codecs.open(replacement_file, "r", "utf-8") as f:
                # strip newlines, but not other characters
                file_replacements = f.read().splitlines()
        except (IOError, OSError) as e:
            pywikibot.error("Error loading {0}: {1}".format(replacement_file, e))
            return False

        if len(file_replacements) % 2:
            pywikibot.error("{0} contains an incomplete pattern replacement pair.".format(replacement_file))
开发者ID:PersianWikipedia,项目名称:pywikibot-core,代码行数:67,代码来源:replace.py


示例12: main

def main(*args):
    """
    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 = {}
    # what the bot should do (either resolve double redirs, or delete broken
    # redirs)
    action = None
    # where the bot should get his infos from (either None to load the
    # maintenance special page from the live wiki, or the filename of a
    # local XML dump file)
    xmlFilename = None
    # Which namespace should be processed when using a XML dump
    # default to -1 which means all namespaces will be processed
    namespaces = []
    # at which redirect shall we start searching double redirects again
    # (only with dump); default to -1 which means all redirects are checked
    offset = -1
    moved_pages = False
    fullscan = False
    start = ''
    until = ''
    number = None
    pagename = None

    for arg in pywikibot.handle_args(args):
        arg, sep, value = arg.partition(':')
        option = arg[1:]
        # bot options
        if arg == 'do':
            action = 'double'
        elif arg == 'br':
            action = 'broken'
        elif arg in ('both', 'broken', 'double'):
            action = arg
        elif option in ('always', 'delete'):
            options[option] = True
        elif option == 'total':
            options['number'] = number = int(value)
        # generator options
        elif option == 'fullscan':
            fullscan = True
        elif option == 'xml':
            xmlFilename = value or i18n.input('pywikibot-enter-xml-filename')
        elif option == 'moves':
            moved_pages = True
        elif option == 'namespace':
            # "-namespace:" does NOT yield -namespace:0 further down the road!
            ns = value or i18n.input('pywikibot-enter-namespace-number')
            # TODO: at least for some generators enter a namespace by its name
            # or number
            if ns == '':
                ns = '0'
            try:
                ns = int(ns)
            except ValueError:
                # -namespace:all Process all namespaces.
                # Only works with the API read interface.
                pass
            if ns not in namespaces:
                namespaces.append(ns)
        elif option == 'offset':
            offset = int(value)
        elif option == 'start':
            start = value
        elif option == 'until':
            until = value
        elif option == 'page':
            pagename = value
        # deprecated or unknown options
        elif option == 'step':
            issue_deprecation_warning('The usage of "{0}"'.format(arg),
                                      2, ArgumentDeprecationWarning)
        else:
            pywikibot.output(u'Unknown argument: {0!s}'.format(arg))

    if not action or xmlFilename and (moved_pages or fullscan):
        problems = []
        if xmlFilename and moved_pages:
            problems += ['Either use a XML file or the moved pages from the API']
        if xmlFilename and fullscan:
            problems += ['Either use a XML file or do a full scan using the API']
        pywikibot.bot.suggest_help(additional_text='\n'.join(problems),
                                   missing_action=not action)
    else:
        pywikibot.Site().login()
        gen = RedirectGenerator(xmlFilename, namespaces, offset, moved_pages,
                                fullscan, start, until, number, pagename)
        bot = RedirectRobot(action, gen, **options)
        bot.run()
开发者ID:runt18,项目名称:pywikibot-core,代码行数:95,代码来源:redirect.py


示例13: main

def main(*args):
    """
    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 = {}
    gen_options = {}
    # what the bot should do (either resolve double redirs, or process broken
    # redirs)
    action = None
    namespaces = []
    source = set()

    for arg in pywikibot.handle_args(args):
        arg, sep, value = arg.partition(':')
        option = arg.partition('-')[2]
        # bot options
        if arg == 'do':
            action = 'double'
        elif arg == 'br':
            action = 'broken'
        elif arg in ('both', 'broken', 'double'):
            action = arg
        elif option in ('always', 'delete'):
            options[option] = True
        elif option == 'total':
            options[option] = gen_options[option] = int(value)
        elif option == 'sdtemplate':
            options['sdtemplate'] = value or pywikibot.input(
                'Which speedy deletion template to use?')
        # generator options
        elif option in ('fullscan', 'moves'):
            gen_options[option] = True
            source.add(arg)
        elif option == 'xml':
            gen_options[option] = value or i18n.input(
                'pywikibot-enter-xml-filename')
            source.add(arg)
        elif option == 'namespace':
            # "-namespace:" does NOT yield -namespace:0 further down the road!
            ns = value or i18n.input('pywikibot-enter-namespace-number')
            # TODO: at least for some generators enter a namespace by its name
            # or number
            if ns == '':
                ns = '0'
            try:
                ns = int(ns)
            except ValueError:
                # -namespace:all Process all namespaces.
                # Only works with the API read interface.
                pass
            if ns not in namespaces:
                namespaces.append(ns)
        elif option == 'offset':
            gen_options[option] = int(value)
        elif option in ('page', 'start', 'until'):
            gen_options[option] = value
        # deprecated or unknown options
        elif option == 'step':
            issue_deprecation_warning('The usage of "{0}"'.format(arg),
                                      2, ArgumentDeprecationWarning)
        else:
            pywikibot.output(u'Unknown argument: %s' % arg)

    gen_options['namespaces'] = namespaces

    if len(source) > 1:
        problem = 'You can only use one of {0} options.'.format(
            ' or '.join(source))
        pywikibot.bot.suggest_help(additional_text=problem,
                                   missing_action=not action)
        return
    if not action:
        pywikibot.bot.suggest_help(missing_action=True)
    else:
        pywikibot.Site().login()
        options['generator'] = RedirectGenerator(action, **gen_options)
        bot = RedirectRobot(action, **options)
        bot.run()
开发者ID:magul,项目名称:pywikibot-core,代码行数:83,代码来源:redirect.py


示例14: twtranslate


#.........这里部分代码省略.........
    >>> from pywikibot import i18n
    >>> i18n.set_messages_package('tests.i18n')
    >>> # use a dictionary
    >>> str(i18n.twtranslate('en', 'test-plural', {'num':2}))
    'Bot: Changing 2 pages.'
    >>> # use additional format strings
    >>> str(i18n.twtranslate('fr', 'test-plural', {'num': 1, 'descr': 'seulement'}))
    'Robot: Changer seulement une page.'
    >>> # use format strings also outside
    >>> str(i18n.twtranslate('fr', 'test-plural', {'num': 10}, only_plural=True)
    ...     % {'descr': 'seulement'})
    'Robot: Changer seulement quelques pages.'

    @param source: When it's a site it's using the lang attribute and otherwise
        it is using the value directly.
    @type source: BaseSite or str
    @param twtitle: The TranslateWiki string title, in <package>-<key> format
    @param parameters: For passing parameters. It should be a mapping but for
        backwards compatibility can also be a list, tuple or a single value.
        They are also used for plural entries in which case they must be a
        Mapping and will cause a TypeError otherwise.
    @param fallback: Try an alternate language code
    @type fallback: boolean
    @param only_plural: Define whether the parameters should be only applied to
        plural instances. If this is False it will apply the parameters also
        to the resulting string. If this is True the placeholders must be
        manually applied afterwards.
    @type only_plural: bool
    @raise IndexError: If the language supports and requires more plurals than
        defined for the given translation template.
    """
    if not messages_available():
        raise TranslationError(
            'Unable to load messages package %s for bundle %s'
            '\nIt can happen due to lack of i18n submodule or files. '
            'Read %s/i18n'
            % (_messages_package_name, twtitle, __url__))

    source_needed = False
    # If a site is given instead of a lang, use its language
    if hasattr(source, 'lang'):
        lang = source.lang
    # check whether we need the language code back
    elif isinstance(source, list):
        # For backwards compatibility still support lists, when twntranslate
        # was not deprecated and needed a way to get the used language code back
        warn('The source argument should not be a list but either a BaseSite '
             'or a str/unicode.', DeprecationWarning, 2)
        lang = source.pop()
        source_needed = True
    else:
        lang = source

    # There are two possible failure modes: the translation dict might not have
    # the language altogether, or a specific key could be untranslated. Both
    # modes are caught with the KeyError.
    langs = [lang]
    if fallback:
        langs += _altlang(lang) + ['en']
    for alt in langs:
        trans = _get_translation(alt, twtitle)
        if trans:
            break
    else:
        raise TranslationError(
            'No %s translation has been defined for TranslateWiki key'
            ' %r\nIt can happen due to lack of i18n submodule or files. '
            'Read https://mediawiki.org/wiki/PWB/i18n'
            % ('English' if 'en' in langs else "'%s'" % lang,
               twtitle))
    # send the language code back via the given mutable list parameter
    if source_needed:
        source.append(alt)

    if '{{PLURAL:' in trans:
        # _extract_plural supports in theory non-mappings, but they are
        # deprecated
        if not isinstance(parameters, Mapping):
            raise TypeError('parameters must be a mapping.')
        trans = _extract_plural(alt, trans, parameters)

    # this is only the case when called in twntranslate, and that didn't apply
    # parameters when it wasn't a dict
    if isinstance(parameters, _PluralMappingAlias):
        # This is called due to the old twntranslate function which ignored
        # KeyError. Instead only_plural should be used.
        if isinstance(parameters.source, dict):
            try:
                trans %= parameters.source
            except KeyError:
                pass
        parameters = None

    if parameters is not None and not isinstance(parameters, Mapping):
        issue_deprecation_warning('parameters not being a Mapping', None, 2)

    if not only_plural and parameters:
        return trans % parameters
    else:
        return trans
开发者ID:hasteur,项目名称:g13bot_tools_new,代码行数:101,代码来源:i18n.py


示例15: main

def main(*args):
    """
    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 = {}
    # what the bot should do (either resolve double redirs, or process broken
    # redirs)
    action = None
    # where the bot should get his infos from (either None to load the
    # maintenance special page from the live wiki, or the filename of a
    # local XML dump file)
    xmlFilename = None
    # Which namespace should be processed when using a XML dump
    # default to -1 which means all namespaces will be processed
    namespaces = []
    # at which redirect shall we start searching double redirects again
    # (only with dump); default to -1 which means all redirects are checked
    offset = -1
    moved_pages = False
    fullscan = False
    start = ""
    until = ""
    number = None
    pagename = None

    for arg in pywikibot.handle_args(args):
        arg, sep, value = arg.partition(":")
        option = arg[1:]
        # bot options
        if arg == "do":
            action = "double"
        elif arg == "br":
            action = "broken"
        elif arg in ("both", "broken", "double"):
            action = arg
        elif option in ("always", "delete"):
            options[option] = True
        elif option == "total":
            options["number"] = number = int(value)
        # generator options
        elif option == "fullscan":
            fullscan = True
        elif option == "xml":
            xmlFilename = value or i18n.input("pywikibot-enter-xml-filename")
        elif option == "moves":
            moved_pages = True
        elif option == "namespace":
            # "-namespace:" does NOT yield -namespace:0 further down the road!
            ns = value or i18n.input("pywikibot-enter-namespace-number")
            # TODO: at least for some generators enter a namespace by its name
            # or number
            if ns == "":
                ns = "0"
            try:
                ns = int(ns)
            except ValueError:
                # -namespace:all Process all namespaces.
                # Only works with the API read interface.
                pass
            if ns not in namespaces:
                namespaces.append(ns)
        elif option == "offset":
            offset = int(value)
        elif option == "start":
            start = value
        elif option == "until":
            until = value
        elif option == "page":
            pagename = value
        # deprecated or unknown options
        elif option == "step":
            issue_deprecation_warning('The usage of "{0}"'.format(arg), 2, ArgumentDeprecationWarning)
        else:
            pywikibot.output("Unknown argument: %s" % arg)

    if not action or xmlFilename and (moved_pages or fullscan):
        problems = []
        if xmlFilename and moved_pages:
            problems += ["Either use a XML file or the moved pages from the API"]
        if xmlFilename and fullscan:
            problems += ["Either use a XML file or do a full scan using the API"]
        pywikibot.bot.suggest_help(additional_text="\n".join(problems), missing_action=not action)
    else:
        pywikibot.Site().login()
        gen = RedirectGenerator(xmlFilename, namespaces, offset, moved_pages, fullscan, start, until, number, pagename)
        bot = RedirectRobot(action, gen, **options)
        bot.run()
开发者ID:PersianWikipedia,项目名称:pywikibot-core,代码行数:92,代码来源:redirect.py


示例16: main

def main(*args):
    """
    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 = {}
    gen = None

    local_args = pywikibot.handle_args(args)

    # This factory is responsible for processing command line arguments
    # that are also used by other scripts and that determine on which pages
    # to work on.
    genFactory = pagegenerators.GeneratorFactory(positional_arg_name='page')

    for arg in local_args:
        option, sep, value = arg.partition(':')
        if option == '-xml':
            filename = value or pywikibot.input(
                "Please enter the XML dump's filename:")
            gen = TableXmlDumpPageGenerator(filename)
        elif option == '-auto':
            issue_deprecation_warning(
                'The usage of "-auto"', '-always',
                1, ArgumentDeprecationWarning)
            options['always'] = True
        elif option in ['-always', '-quiet', '-skipwarning']:
            options[option[1:]] = True
        else:
            if option in ['-sql', '-mysqlquery']:
                if not (has_module('oursql') or has_module('MySQLdb')):
                    raise NotImplementedError(
                        'Neither "oursql" nor "MySQLdb" library is installed.')
                if option == '-sql':
                    issue_deprecation_warning(
                        'The usage of "-sql"', '-mysqlquery',
                        1, ArgumentDeprecationWarning)

                query = value or """
SELECT page_namespace, page_title
FROM page JOIN text ON (page_id = old_id)
WHERE old_text LIKE '%<table%'
"""
                arg = '-mysqlquery:' + query
            genFactory.handleArg(arg)

    if gen:
        gen = pagegenerators.NamespaceFilterPageGenerator(
            gen, genFactory.namespaces)
    else:
        gen = genFactory.getCombinedGenerator()

    if gen:
        if not genFactory.nopreload:
            gen = pagegenerators.PreloadingGenerator(gen)
        bot = Table2WikiRobot(generator=gen, **options)
        bot.run()
        return True
    else:
        suggest_help(missing_generator=True)
        return False
开发者ID:magul,项目名称:pywikibot-core,代码行数:65,代码来源:table2wiki.py


示例17: main

def main(*args):
    """
    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
    """
    gen = None
    oldName = None
    options = {}
    fromToPairs = []

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

    for arg in local_args:
        if arg.startswith('-pairs'):
            issue_deprecation_warning(
                '-pairs',
                '-pairsfile',
                2, ArgumentDeprecationWarning)
        elif arg.startswith('-pairsfile'):
            if len(arg) == len('-pairsfile'):
                filename = pywikibot.input(
                    u'Enter the name of the file containing pairs:')
            else:
                filename = arg[len('-pairsfile:'):]
            oldName1 = None
            for page in pagegenerators.TextfilePageGenerator(filename):
                if oldName1:
                    fromToPairs.append([oldName1, page.title()])
                    oldName1 = None
                else:
                    oldName1 = page.title()
            if oldName1:
                pywikibot.warning(
                    u'file %s contains odd number of links' % filename)
        elif arg == '-noredirect':
            options['noredirect'] = True
        elif arg == '-notalkpage':
            options['movetalkpage'] = False
        elif arg == '-always':
            options['always'] = True
        elif arg == '-skipredirects':
            options['skipredirects'] = True
        elif arg.startswith('-from:'):
            if oldName:
                pywikibot.warning(u'-from:%s without -to:' % oldName)
            oldName = arg[len('-from:'):]
        elif arg.startswith('-to:'):
            if oldName:
                fromToPairs.append([oldName, arg[len('-to:'):]])
                oldName = None
            else:
                pywikibot.warning(u'%s without -from' % arg)
        elif arg.startswith('-prefix'):
            if len(arg) == len('-prefix'):
                options['prefix'] = pywikibot.input(u'Enter the prefix:')
            else:
                options['prefix'] = arg[8:]
        elif arg.startswith('-summary'):
            if len(arg) == len('-summary'):
                options['summary'] = pywikibot.input(u'Enter the summary:')
            else:
                options['summary'] = arg[9:]
        else:
            genFactory.handleArg(arg)

    if oldName:
        pywikibot.warning(u'-from:%s without -to:' % oldName)
    site = pywikibot.Site()
    for pair in fromToPairs:
        page = pywikibot.Page(site, pair[0])
        bot = MovePagesBot(None, **options)
        bot.moveOne(page, pair[1])

    if not gen:
        gen = genFactory.getCombinedGenerator()
    if gen:
        preloadingGen = pagegenerators.PreloadingGenerator(gen)
        bot = MovePagesBot(preloadingGen, **options)
        bot.run()
        return True

    if not fromToPairs:
        pywikibot.bot.suggest_help(missing_generator=True)
        return False
    else:
        return True
开发者ID:AbdealiJK,项目名称:pywikibot-core,代码行数:92,代码来源:movepages.py


示例18: translate

def translate(code, xdict, parameters=None, fallback=False):
    """Return the most appropriate translation from a translation dict.

    Given a language code and a dictionary, returns the dictionary's value for
    key 'code' if this key exists; otherwise tries to return a value for an
    alternative language that is most applicable to use on the wiki in
    language 'code' except fallback is False.

    The language itself is always checked first, then languages that
    have been defined to be alternatives, and finally English. If none of
    the options gives result, we just take the one language from xdict which may
    not be always the same. When fallback is iterable it'll return None if no
    code applies (instead of returning one).

    For PLURAL support have a look at the twtranslate method.

    @param code: The language code
    @type code: string or Site object
    @param xdict: dictionary with language codes as keys or extended dictionary
                  with family names as keys containing language dictionaries or
                  a single (unicode) string. May contain PLURAL tags as
                  described in twtranslate
    @type xdict: dict, string, unicode
    @param parameters: For passing (plural) parameters
    @type parameters: dict, string, unicode, int
    @param fallback: Try an alternate language code. If it's iterable it'll
        also try those entries and choose the first match.
    @type fallback: boolean or iterable
    @raise IndexError: If the language supports and requires more plurals than
        defined for the given translation template.
    """
    family = pywikibot.config.family
    # If a site is given instead of a code, use its language
    if hasattr(code, 'code'):
        family = code.family.name
        code = code.code

    # Check whether xdict has multiple projects
    if isinstance(xdict, dict):
        if family in xdict:
            xdict = xdict[family]
        elif 'wikipedia' in xdict:
            xdict = xdict['wikipedia']

    # Get the translated string
    if not isinstance(xdict, dict):
        trans = xdict
    elif not xdict:
        trans = None
    else:
        codes = [code]
        if fallback is True:
            codes += _altlang(code) + ['_default', 'en']
        elif fallback is not False:
            codes += list(fallback)
        for code in codes:
            if code in xdict:
                trans = xdict[code]
                break
        else:
            if fallback is not True:
                # this shouldn't simply return "any one" code but when fallback
                # was True before 65518573d2b0, it did just that. When False it
                # did just return None. It's now also returning None in the new
                # iterable mode.
                return
            code = list(xdict.keys())[0]
            trans = xdict[code]
    if trans is None:
        return  # return None if we have no translation found
    if parameters is None:
        return trans

    if not isinstance(parameters, Mapping):
        issue_deprec 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python formatter.color_format函数代码示例发布时间:2022-05-26
下一篇:
Python tools.first_lower函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap