本文整理汇总了Python中pywikibot.tools.issue_deprecation_warning函数的典型用法代码示例。如果您正苦于以下问题:Python issue_deprecation_warning函数的具体用法?Python issue_deprecation_warning怎么用?Python issue_deprecation_warning使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了issue_deprecation_warning函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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()
示例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]
示例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)
示例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()
示例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
示例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
示例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')
示例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")
示例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
示例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]
示例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))
示例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()
示例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()
示例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
示例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()