本文整理汇总了Python中wikipedia.warning函数的典型用法代码示例。如果您正苦于以下问题:Python warning函数的具体用法?Python warning怎么用?Python warning使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了warning函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load
def load(self, page):
"""
Loads the given page, does some changes, and saves it.
"""
try:
# Load the page
text = page.get()
except pywikibot.NoPage:
if self.create:
pywikibot.output(u"Page %s doesn't exist yet; creating."
% (page.title(asLink=True)))
text = ''
else:
pywikibot.output(u"Page %s does not exist; skipping."
% page.title(asLink=True))
except pywikibot.IsRedirectPage:
redirTarget = page.getRedirectTarget()
if self.follow_redirects:
text = redirTarget.get()
else:
pywikibot.warning(u"Page %s is a redirect to %s; skipping."
% (page.title(asLink=True),
redirTarget.title(asLink=True)))
else:
return text
示例2: main
def main():
pywikibot.warning("this script should not be run manually/directly, but automatically by maintainer.py")
if len(sys.argv) == 1:
pywikibot.output("Usage: censure.py <article title>")
sys.exit(1)
del sys.argv[0]
checkPage(" ".join(sys.argv).decode("utf-8"))
示例3: getOpenStreetMap
def getOpenStreetMap(latitude, longitude):
'''
Get the result from http://nominatim.openstreetmap.org/reverse
and put it in a list of tuples to play around with
'''
result = []
gotInfo = False
parameters = urllib.urlencode({'lat' : latitude, 'lon' : longitude, 'accept-language' : 'en'})
while(not gotInfo):
try:
page = urllib.urlopen("http://nominatim.openstreetmap.org/reverse?format=xml&%s" % parameters)
et = xml.etree.ElementTree.parse(page)
gotInfo=True
except IOError:
pywikibot.output(u'Got an IOError, let\'s try again')
time.sleep(30)
except socket.timeout:
pywikibot.output(u'Got a timeout, let\'s try again')
time.sleep(30)
validParts = [u'hamlet', u'village', u'city', u'county', u'country']
invalidParts = [u'path', u'road', u'suburb', u'state', u'country_code']
addressparts = et.find('addressparts')
#xml.etree.ElementTree.dump(et)
for addresspart in addressparts.getchildren():
if addresspart.tag in validParts:
result.append(addresspart.text)
elif addresspart.tag in invalidParts:
pywikibot.output(u'Dropping %s, %s' % (addresspart.tag, addresspart.text))
else:
pywikibot.warning(u'%s, %s is not in addressparts lists' % (addresspart.tag, addresspart.text))
#print result
return result
示例4: do_check
def do_check(self, page_title, params=None):
# Create two threads as follows
# (simple 'thread' for more sophisticated code use 'threading')
pywikibot.output(u"CHECK: %s" % page_title)
try:
thread.start_new_thread( main_subster, (self.refs[page_title], params) )
except:
pywikibot.warning(u"unable to start thread")
示例5: parse
def parse(self):
"""Return a generator that will yield XmlEntry objects"""
print 'Reading XML dump...'
if 'iterparse' not in globals():
pywikibot.warning(
u'''cElementTree not found. Using slower fallback solution.
Consider installing the python-celementtree package.''')
return self.regex_parse()
else:
return self.new_parse()
示例6: main
def main():
pywikibot.warning(u"This script will set preferences on all " u"configured accounts!")
pywikibot.output(
u"You have %s accounts configured." % sum([len(family) for family in config.usernames.itervalues()])
)
if pywikibot.inputChoice(u"Do you wish to continue?", ["no", "yes"], ["n", "y"], "n") == "n":
return
if (
pywikibot.inputChoice(
u"Do you already know which preference you wish " u"to set?", ["no", "yes"], ["n", "y"], "y"
)
== "n"
):
site = pywikibot.getSite()
pywikibot.output(u"Getting list of available preferences from %s." % site)
prefs = Preferences(site)
pywikibot.output(u"-" * 73)
pywikibot.output(u"| Name | Value |")
pywikibot.output(u"-" * 73)
pref_data = prefs.items()
pref_data.sort()
for key, value in pref_data:
pywikibot.output(table_cell(key, 4) + table_cell(value, 5) + "|")
pywikibot.output(u"-" * 73)
pywikibot.output(u"")
pywikibot.output(u"(For checkboxes: An empty string evaluates to False; " u"all others to True)")
pywikibot.output(u"")
while True:
keys, values = [], []
while True:
try:
keys.append(pywikibot.input(u"Which preference do you wish to set?"))
except KeyboardInterrupt:
return
values.append(pywikibot.input(u"To what value do you wish to set '%s'?" % keys[-1]))
if pywikibot.inputChoice(u"Set more preferences?", ["no", "yes"], ["n", "y"], "n") == "n":
break
if (
pywikibot.inputChoice(
u"Set %s?" % u", ".join(u"%s:%s" % (key, value) for key, value in zip(keys, values)),
["yes", "no"],
["y", "n"],
"n",
)
== "y"
):
set_all(keys, values, verbose=True)
pywikibot.output(u"Preferences have been set on all wikis.")
示例7: __init__
def __init__(self):
'''Constructor of SubsterBot(), initialize needed vars.'''
pywikibot.output(u'\03{lightgreen}* Initialization of bot:\03{default}')
basic.AutoBasicBot.__init__(self)
# modification of timezone to be in sync with wiki
os.environ['TZ'] = 'Europe/Amsterdam'
if hasattr(time, "tzset"):
time.tzset()
pywikibot.output(u'Setting process TimeZone (TZ): %s'
% str(time.tzname)) # ('CET', 'CEST')
else:
# e.g. windows doesn't have that attribute
pywikibot.warning(
u'This operating system has NO SUPPORT for setting TimeZone by '
u'code! Before running this script, please set the TimeZone '
u'manually to one approriate for use with the Wikipedia '
u'language and region you intend to.')
# init constants
self._bot_config = bot_config
# convert e.g. namespaces to corret language
self._bot_config['TemplateName'] = pywikibot.Page(
self.site, self._bot_config['TemplateName']).title()
self._template_regex = re.compile(
'\{\{' + self._bot_config['TemplateName'] + '(.*?)\}\}', re.S)
# TODO: implement proper error handling template/output for wikidata
# see: https://bugzilla.wikimedia.org/show_bug.cgi?id=60225
# see: https://www.wikidata.org/wiki/Template:Exchange_Rate_Data
#if self.site.is_data_repository():
# self._bot_config['VerboseMessage'] = self._bot_config['data_VerboseMessage']
# init constants
self._userListPage = pywikibot.Page(self.site,
self._bot_config['TemplateName'])
self._ConfCSSpostprocPage = pywikibot.Page(
self.site, self._bot_config['ConfCSSpostproc'])
self._ConfCSSconfigPage = pywikibot.Page(
self.site, self._bot_config['ConfCSSconfig'])
self.pagegen = pagegenerators.ReferringPageGenerator(
self._userListPage, onlyTemplateInclusion=True)
self._code = self._ConfCSSpostprocPage.get()
pywikibot.output(u'Imported postproc %s rev %s from %s'
% ((self._ConfCSSpostprocPage.title(asLink=True), )
+ self._ConfCSSpostprocPage.getVersionHistory(revCount=1)[0][:2]))
self._flagenable = {}
if self._ConfCSSconfigPage.exists():
exec(self._ConfCSSconfigPage.get()) # with variable: bot_config_wiki
self._flagenable = bot_config_wiki['flagenable']
pywikibot.output(u'Imported config %s rev %s from %s'
% ((self._ConfCSSconfigPage.title(asLink=True), )
+ self._ConfCSSconfigPage.getVersionHistory(revCount=1)[0][:2]))
示例8: main
def main():
pywikibot.warning(u'This script will set preferences on all '
u'configured accounts!')
pywikibot.output(u'You have %s accounts configured.'
% sum([len(family)
for family in config.usernames.itervalues()]))
if pywikibot.inputChoice(u'Do you wish to continue?',
['no', 'yes'], ['n', 'y'], 'n') == 'n':
return
if pywikibot.inputChoice(u'Do you already know which preference you wish '
u'to set?', ['no', 'yes'], ['n', 'y'], 'y') == 'n':
site = pywikibot.getSite()
pywikibot.output(u'Getting list of available preferences from %s.'
% site)
prefs = Preferences(site)
pywikibot.output(u'-' * 73)
pywikibot.output(u'| Name | Value |')
pywikibot.output(u'-' * 73)
pref_data = prefs.items()
pref_data.sort()
for key, value in pref_data:
pywikibot.output(table_cell(key, 4) + table_cell(value, 5) + '|')
pywikibot.output(u'-' * 73)
pywikibot.output(u'')
pywikibot.output(u'(For checkboxes: An empty string evaluates to False; '
u'all others to True)')
pywikibot.output(u'')
while True:
keys, values = [], []
while True:
try:
keys.append(pywikibot.input(
u'Which preference do you wish to set?'))
except KeyboardInterrupt:
return
values.append(pywikibot.input(
u"To what value do you wish to set '%s'?" % keys[-1]))
if pywikibot.inputChoice(u"Set more preferences?",
['no', 'yes'], ['n', 'y'], 'n') == 'n':
break
if pywikibot.inputChoice(
u"Set %s?"
% u', '.join(u'%s:%s' % (key, value)
for key, value in zip(keys, values)),
['yes', 'no'], ['y', 'n'], 'n') == 'y':
set_all(keys, values, verbose=True)
pywikibot.output(u"Preferences have been set on all wikis.")
示例9: handleNextLink
def handleNextLink(self, page, text, match, context=100):
"""
Returns a tuple (text, jumpToBeginning).
text is the unicode string after the current link has been processed.
jumpToBeginning is a boolean which specifies if the cursor position
should be reset to 0. This is required after the user has edited the
article.
"""
# ignore interwiki links and links to sections of the same page as well
# as section links
if not match.group("title") or page.site().isInterwikiLink(match.group("title")) or match.group("section"):
return text, False
try:
linkedPage = pywikibot.Page(page.site(), match.group("title"))
except pywikibot.InvalidTitle, err:
pywikibot.warning(u"%s" % err)
return text, False
示例10: fix_1_double_redirect
def fix_1_double_redirect(self, redir_name):
redir = pywikibot.Page(self.site, redir_name)
# Show the title of the page we're working on.
# Highlight the title in purple.
pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
% redir.title())
newRedir = redir
redirList = [] # bookkeeping to detect loops
while True:
redirList.append(u'%s:%s' % (newRedir.site.lang,
newRedir.sectionFreeTitle()))
try:
targetPage = newRedir.getRedirectTarget()
except pywikibot.IsNotRedirectPage:
if len(redirList) == 1:
pywikibot.output(u'Skipping: Page %s is not a redirect.'
% redir.title(asLink=True))
break # do nothing
elif len(redirList) == 2:
pywikibot.output(
u'Skipping: Redirect target %s is not a redirect.'
% newRedir.title(asLink=True))
break # do nothing
else:
pass # target found
except pywikibot.SectionError:
pywikibot.warning(
u"Redirect target section %s doesn't exist."
% newRedir.title(asLink=True))
except pywikibot.BadTitle as e:
# str(e) is in the format 'BadTitle: [[Foo]]'
pywikibot.warning(
u'Redirect target %s is not a valid page title.'
% str(e)[10:])
# sometimes this error occures. Invalid Title starting with a '#'
except pywikibot.InvalidTitle, err:
pywikibot.warning(u'%s' % err)
break
except pywikibot.NoPage:
if len(redirList) == 1:
pywikibot.output(u'Skipping: Page %s does not exist.'
% redir.title(asLink=True))
break
else:
if self.always:
pywikibot.output(
u"Skipping: Redirect target %s doesn't exist."
% newRedir.title(asLink=True))
break # skip if automatic
else:
pywikibot.warning(
u"Redirect target %s doesn't exist."
% newRedir.title(asLink=True))
示例11: set_all
def set_all(keys, values, verbose=False):
log = open('preferences.txt', 'a')
log.write('PREFERENCES\t%s\n' % time.gmtime())
log.write('KEYS\t%s\n' % keys)
log.write('VALUES\t%s\n' % values)
for family in config.usernames:
for lang in config.usernames[family]:
try:
set_for(lang, family, keys, values, verbose)
except (SystemExit, KeyboardInterrupt):
return
except:
pywikibot.exception(tb=True)
pywikibot.warning(u'An exception occured!')
log.write('FAILED\t%s\t%s\n' % (family, lang))
else:
log.write('SUCCESS\t%s\t%s\n' % (family, lang))
log.close()
示例12: main
def main(args):
pywikibot.warnnig(u'This is an experimental bot')
pywikibot.warning(u'It will only work on self published work images')
pywikibot.warning(u'This bot is still full of bugs')
pywikibot.warning(u'Use at your own risk!')
generator = None
autonomous = False
checkTemplate = True
# Load a lot of default generators
genFactory = pagegenerators.GeneratorFactory()
for arg in pywikibot.handleArgs():
if arg == '-nochecktemplate':
checkTemplate = False
elif arg == '-autonomous':
autonomous = True
else:
genFactory.handleArg(arg)
if not supportedSite():
pywikibot.output(u'Sorry, this site is not supported (yet).')
return False
generator = genFactory.getCombinedGenerator()
if not generator:
raise add_text.NoEnoughData(
'You have to specify the generator you want to use for the script!')
pregenerator = pagegenerators.PreloadingGenerator(generator)
prefetchQueue = Queue(maxsize=50)
uploadQueue = Queue(maxsize=200)
imageFetcherThread = imageFetcher(pregenerator, prefetchQueue)
userInteractionThread = userInteraction(prefetchQueue, uploadQueue)
uploaderThread = uploader(uploadQueue)
imageFetcherThread.daemon = False
userInteractionThread.daemon = False
uploaderThread.daemon = False
if autonomous:
pywikibot.output(u'Bot is running in autonomous mode. There will be no '
u'user interaction.')
userInteractionThread.setAutonomous()
if not checkTemplate:
pywikibot.output(u'No check template will be added to the uploaded '
u'files.')
uploaderThread.nochecktemplate()
fetchDone = imageFetcherThread.start()
userDone = userInteractionThread.start()
uploadDone = uploaderThread.start()
示例13: main
def main():
password = None
sysop = False
logall = False
forceLogin = False
verbose = False
clean = False
testonly = False
for arg in pywikibot.handleArgs():
if arg.startswith("-pass"):
if len(arg) == 5:
password = pywikibot.input(u'Password for all accounts '
u'(no characters will be shown):',
password=True)
else:
password = arg[6:]
elif arg == "-clean":
clean = True
elif arg == "-sysop":
sysop = True
elif arg == "-all":
logall = True
elif arg == "-force":
forceLogin = True
elif arg == "-test":
testonly = True
else:
pywikibot.showHelp('login')
return
if pywikibot.verbose > 1:
pywikibot.warning(u"""
Using -v -v on login.py might leak private data. When sharing, please double
check your password is not readable and log out your bots session.""")
verbose = True # only use this verbose when running from login.py
if logall:
if sysop:
namedict = config.sysopnames
else:
namedict = config.usernames
for familyName in namedict.iterkeys():
for lang in namedict[familyName].iterkeys():
if testonly:
show(pywikibot.getSite(lang, familyName), sysop)
else:
try:
site = pywikibot.getSite(lang, familyName)
loginMan = LoginManager(password, sysop=sysop,
site=site, verbose=verbose)
if clean:
loginMan.logout()
else:
if not forceLogin and site.loggedInAs(sysop=sysop):
pywikibot.output(u'Already logged in on %s'
% site)
else:
loginMan.login()
except pywikibot.NoSuchSite:
pywikibot.output(lang + u'.' + familyName +
u' is not a valid site, please remove '
u'it from your config')
elif testonly:
show(pywikibot.getSite(), sysop)
elif clean:
try:
site = pywikibot.getSite()
lgm = LoginManager(site=site)
lgm.logout()
except pywikibot.NoSuchSite:
pass
else:
loginMan = LoginManager(password, sysop=sysop, verbose=verbose)
loginMan.login()
示例14: execfile
sys.path.append(os.path.split(sys.argv[0])[0])
execfile(sys.argv[0])
exitcode = ERROR_SGE_ok
pywikibot.output(u"")
pywikibot.output(u"DONE")
except:
pywikibot.exception(tb=True)
error = traceback.format_exc()
if pywikibot.logger.isEnabledFor(pywikibot.DEBUG):
exitcode = ERROR_SGE_ok # print traceback of re-raised errors by skipping sys.exit()
raise
else:
send_mailnotification(error, u"Bot ERROR")
pywikibot.output(u"")
pywikibot.warning(u"DONE with Exception(s) occured in Bot")
finally:
site = pywikibot.getSite()
name = str("%s-%s-%s" % (bot_name, site.family.name, site.lang))
d = shelve.open(pywikibot.config.datafilepath("cache", "state_bots"))
d[name] = {
"error": str(bool(error)),
"traceback": str(error.encode("utf-8")),
"timestamp": str(pywikibot.Timestamp.now().isoformat(" ")),
}
d.close()
pywikibot.stopme()
(sys.stdout, sys.stderr) = (sys.__stdout__, sys.__stderr__)
# use exitcode to control SGE (restart or stop with sending mail)
示例15: main
def main():
gen = None
prefix = None
oldName = None
newName = None
noredirect = False
always = False
skipredirects = False
summary = None
fromToPairs = []
# 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()
for arg in pywikibot.handleArgs():
if arg.startswith('-pairs'):
if len(arg) == len('-pairs'):
filename = pywikibot.input(
u'Enter the name of the file containing pairs:')
else:
filename = arg[len('-pairs:'):]
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':
noredirect = True
elif arg == '-always':
always = True
elif arg == '-skipredirects':
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'):
prefix = pywikibot.input(u'Enter the prefix:')
else:
prefix = arg[8:]
elif arg.startswith('-summary'):
if len(arg) == len('-summary'):
summary = pywikibot.input(u'Enter the summary:')
else:
summary = arg[9:]
else:
genFactory.handleArg(arg)
if oldName:
pywikibot.warning(u'-from:%s without -to:' % oldName)
for pair in fromToPairs:
page = pywikibot.Page(pywikibot.getSite(), pair[0])
bot = MovePagesBot(None, prefix, noredirect, always, skipredirects,
summary)
bot.moveOne(page, pair[1])
if not gen:
gen = genFactory.getCombinedGenerator()
if gen:
preloadingGen = pagegenerators.PreloadingGenerator(gen)
bot = MovePagesBot(preloadingGen, prefix, noredirect, always,
skipredirects, summary)
bot.run()
elif not fromToPairs:
pywikibot.showHelp()