本文整理汇总了Python中pywikibot.inputChoice函数的典型用法代码示例。如果您正苦于以下问题:Python inputChoice函数的具体用法?Python inputChoice怎么用?Python inputChoice使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了inputChoice函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: treat
def treat(self):
page = pywikibot.Page(self.site, self.your_page)
if page.exists():
pywikibot.output(
u"\nWikitable on \03{lightpurple}%s\03{default} will be " u"completed with:\n" % self.your_page
)
text = page.get()
newtext = self.newraw()
pywikibot.output(newtext)
choice = pywikibot.inputChoice(u"Do you want to add these on wikitable?", ["Yes", "No"], ["y", "N"], "N")
text = text[:-3] + newtext
summ = pywikibot.translate(self.site, summary_update)
if choice == "y":
try:
page.put(u"".join(text), summ)
except:
pywikibot.output(u"Impossible to edit. It may be an " u"edit conflict. Skipping...")
else:
pywikibot.output(
u"\nWikitable on \03{lightpurple}%s\03{default} will be " u"created with:\n" % self.your_page
)
newtext = self.newtable() + self.newraw()
pywikibot.output(newtext)
summ = pywikibot.translate(self.site, summary_creation)
choice = pywikibot.inputChoice(u"Do you want to accept this page creation?", ["Yes", "No"], ["y", "N"], "N")
if choice == "y":
try:
page.put(newtext, summ)
except pywikibot.LockedPage:
pywikibot.output(u"Page %s is locked; skipping." % title)
except pywikibot.EditConflict:
pywikibot.output(u"Skipping %s because of edit conflict" % title)
except pywikibot.SpamfilterError, error:
pywikibot.output(u"Cannot change %s because of spam " u"blacklist entry %s" % (title, error.url))
示例2: creerPage
def creerPage(self, text, page, comment, minorEdit=True, botflag=True):
# only save if something was changed
if text != None:
arretdurgence()
# 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} <<<" % page.title())
# show what was changed
#pywikibot.showDiff(page.get(), text)
pywikibot.output(u'%s' % text)
pywikibot.output(u'Comment: %s' %comment)
if not self.dry:
#choice = pywikibot.inputChoice(u'Êtes-vous sûr de vouloir créer la page ?', ['Yes', 'No'], ['y', 'N'], 'N')
choice = 'y'
if choice == 'y':
try:
arretdurgence()
if arret == "Oui":
pywikibot.inputChoice(u"Demande d'arrêt d'urgence",['vu'],['v'],'')
# Save the page
page.put(text, comment=comment,
minorEdit=minorEdit, botflag=botflag)
except pywikibot.LockedPage:
pywikibot.output(u"Page %s is locked; skipping."
% page.title(asLink=True))
except pywikibot.EditConflict:
pywikibot.output(
u'Skipping %s because of edit conflict'
% (page.title()))
except pywikibot.SpamfilterError, error:
pywikibot.output(
u'Cannot change %s because of spam blacklist entry %s'
% (page.title(), error.url))
else:
return True
示例3: process_filename
def process_filename(self):
"""Return base filename portion of self.url"""
# Isolate the pure name
filename = self.url
# Filename may be either a local file path or a URL
if "://" in filename:
# extract the path portion of the URL
filename = urlparse.urlparse(filename).path
filename = os.path.basename(filename)
if self.useFilename:
filename = self.useFilename
if not self.keepFilename:
pywikibot.output(
u"The filename on the target wiki will default to: %s"
% filename)
# FIXME: these 2 belong somewhere else, presumably in family
forbidden = '/' # to be extended
allowed_formats = (u'gif', u'jpg', u'jpeg', u'mid', u'midi',
u'ogg', u'png', u'svg', u'xcf', u'djvu')
# ask until it's valid
while True:
newfn = pywikibot.input(
u'Enter a better name, or press enter to accept:')
if newfn == "":
newfn = filename
break
ext = os.path.splitext(newfn)[1].lower().strip('.')
# are any chars in forbidden also in newfn?
invalid = set(forbidden) & set(newfn)
if invalid:
c = "".join(invalid)
print "Invalid character(s): %s. Please try again" % c
continue
if ext not in allowed_formats:
choice = pywikibot.inputChoice(
u"File format is not one of [%s], but %s. Continue?"
% (u' '.join(allowed_formats), ext),
['yes', 'no'], ['y', 'N'], 'N')
if choice == 'n':
continue
break
if newfn != '':
filename = newfn
# A proper description for the submission.
pywikibot.output(u"The suggested description is:")
pywikibot.output(self.description)
if self.verifyDescription:
newDescription = u''
choice = pywikibot.inputChoice(
u'Do you want to change this description?',
['Yes', 'No'], ['y', 'N'], 'n')
if choice == 'y':
import editarticle
editor = editarticle.TextEditor()
newDescription = editor.edit(self.description)
# if user saved / didn't press Cancel
if newDescription:
self.description = newDescription
return filename
示例4: useHashGenerator
def useHashGenerator(self):
# http://toolserver.org/~multichill/nowcommons.php?language=it&page=2&filter=
lang = self.site.lang
num_page = 0
word_to_skip_translated = i18n.translate(self.site, word_to_skip)
images_processed = list()
while 1:
url = ('http://toolserver.org/~multichill/nowcommons.php?'
'language=%s&page=%s&filter=') % (lang, num_page)
HTML_text = self.site.getUrl(url, no_hostname=True)
reg = r'<[Aa] href="(?P<urllocal>.*?)">(?P<imagelocal>.*?)</[Aa]> +?</td><td>\n\s*?'
reg += r'<[Aa] href="(?P<urlcommons>http://commons.wikimedia.org/.*?)" \
>Image:(?P<imagecommons>.*?)</[Aa]> +?</td><td>'
regex = re.compile(reg, re.UNICODE)
found_something = False
change_page = True
for x in regex.finditer(HTML_text):
found_something = True
image_local = x.group('imagelocal')
image_commons = x.group('imagecommons')
if image_local in images_processed:
continue
change_page = False
images_processed.append(image_local)
# Skip images that have something in the title (useful for it.wiki)
image_to_skip = False
for word in word_to_skip_translated:
if word.lower() in image_local.lower():
image_to_skip = True
if image_to_skip:
continue
url_local = x.group('urllocal')
url_commons = x.group('urlcommons')
pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
% image_local)
pywikibot.output(u'Local: %s\nCommons: %s\n'
% (url_local, url_commons))
result1 = webbrowser.open(url_local, 0, 1)
result2 = webbrowser.open(url_commons, 0, 1)
if image_local.split('Image:')[1] == image_commons:
choice = pywikibot.inputChoice(
u'The local and the commons images have the same name, continue?',
['Yes', 'No'], ['y', 'N'], 'N')
else:
choice = pywikibot.inputChoice(
u'Are the two images equal?',
['Yes', 'No'], ['y', 'N'], 'N')
if choice.lower() in ['y', 'yes']:
yield [image_local, image_commons]
else:
continue
# The page is dinamically updated, so we may don't need to change it
if change_page:
num_page += 1
# If no image found means that there aren't anymore, break.
if not found_something:
break
示例5: reportBadAccount
def reportBadAccount(self, name=None, final=False):
#Queue process
if name:
if globalvar.confirm:
answer = pywikibot.inputChoice(
u'%s may have an unwanted username, do you want to report '
u'this user?' % name,
['Yes', 'No', 'All'], ['y', 'N', 'a'], 'N')
if answer in ['a', 'all']:
answer = 'y'
globalvar.confirm = False
else:
answer = 'y'
if answer.lower() in ['yes', 'y'] or not globalvar.confirm:
showStatus()
pywikibot.output(
u'%s is possibly an unwanted username. It will be reported.'
% name)
if hasattr(self, '_BAQueue'):
self._BAQueue.append(name)
else:
self._BAQueue = [name]
if len(self._BAQueue) >= globalvar.dumpToLog or final:
rep_text = ''
# name in queue is max, put detail to report page
pywikibot.output("Updating badname accounts to report page...")
rep_page = pywikibot.Page(self.site,
pywikibot.translate(self.site,
report_page))
if rep_page.exists():
text_get = rep_page.get()
else:
text_get = u'This is a report page for the Bad-username, please translate me. --~~~'
pos = 0
# The talk page includes "_" between the two names, in this way i
# replace them to " ".
for usrna in self._BAQueue:
username = pywikibot.url2link(usrna, self.site, self.site)
n = re.compile(re.escape(username), re.UNICODE)
y = n.search(text_get, pos)
if y:
pywikibot.output(u'%s is already in the report page.'
% username)
else:
# Adding the log.
rep_text += pywikibot.translate(self.site, report_text) % username
if self.site.code == 'it':
rep_text = "%s%s}}" % (rep_text, self.bname[username])
com = i18n.twtranslate(self.site, 'welcome-bad_username')
if rep_text != '':
rep_page.put(text_get + rep_text, comment=com, force=True,
minorEdit=True)
showStatus(5)
pywikibot.output(u'Reported')
self.BAQueue = list()
else:
return True
示例6: save
def save(self, text, page, comment=None, minorEdit=True,
botflag=True):
# only save if something was changed
saveres=False
if self.text != text:
if not self.dry:
if self.manual:
# 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} <<<"
% page.title())
# show what was changed
pywikibot.showDiff(page.get(), text)
logger.info(u'Comment: %s' %comment)
choice = pywikibot.inputChoice(
u'Do you want to accept these changes?',
['Yes', 'No'], ['y', 'N'], 'N')
if (not self.manual) or (self.manual and choice == 'y'):
logger.debug("Saving ...")
saveres=self._save(page,text,comment,minorEdit,botflag)
else:
logger.debug("Changes discarded - doing nothing")
else:
logger.debug("Nothing changed - doing nothing")
if saveres:
logger.info("Changes saved")
else:
logger.info("Nothing done")
return saveres
示例7: treat
def treat(self, page):
try:
# 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} <<<" % page.title())
ccToolkit = CosmeticChangesToolkit(
page.site, debug=True, namespace=page.namespace(), pageTitle=page.title()
)
changedText = ccToolkit.change(page.get())
if changedText.strip() != page.get().strip():
if not self.acceptall:
choice = pywikibot.inputChoice(
u"Do you want to accept these changes?", ["Yes", "No", "All", "Quit"], ["y", "N", "a", "q"], "N"
)
if choice == "a":
self.acceptall = True
elif choice == "q":
self.done = True
return
if self.acceptall or choice == "y":
page.text = changedText
page.save(comment=self.comment, async=self.async)
else:
pywikibot.output("No changes were necessary in %s" % page.title())
except pywikibot.NoPage:
pywikibot.output("Page %s does not exist?!" % page.title(asLink=True))
except pywikibot.IsRedirectPage:
pywikibot.output("Page %s is a redirect; skipping." % page.title(asLink=True))
except pywikibot.LockedPage:
pywikibot.output("Page %s is locked?!" % page.title(asLink=True))
except pywikibot.EditConflict:
pywikibot.output("An edit conflict has occured at %s." % page.title(asLink=True))
示例8: delete_item
def delete_item(item, other, msg=None, by=site.user(), rfd=False, allow_sitelinks=False, askmerge=False):
item.get(force=True)
other.get(force=True)
if allow_sitelinks is not True and len(item.sitelinks) > 0:
error_merge_msg(item, other)
return False
if compare(item, other, 'sitelinks') is False or compare(item, other, 'labels') is False or compare(item, other, 'descriptions') is False:
if askmerge and pywikibot.inputChoice(u'force merging?', ['Yes', 'No'], ['Y', 'N'], 'N').strip().lower() in ['yes', 'y']:
merge_items((other, item), force_lower=False, taxon_mode=False)
return False
if by is None:
by = item.site.data_repository().user()
for key in item.aliases:
for alias in item.aliases[key]:
if alias.strip() != '' and ((key not in other.aliases) or (alias not in other.aliases[key])):
error_merge_msg(item, other)
return False
for prop in item.claims:
if (prop not in other.claims) or len(list(set([claim.getTarget() for claim in item.claims[prop]])-set([claim.getTarget() for claim in other.claims[prop]]))):
error_merge_msg(item, other)
return False
if rfd:
rfd_page = pywikibot.Page(site, 'Requests for deletions', ns=4)
rfd_page.get(force=True)
if msg is None:
msg = u'Merged with {other}{by}'.format(other=other.getID(), by=(u' by [[User:{0}|{0}]]'.format(by) if by != site.user() else ''))
rfd_page.text += u'\n\n{{{{subst:Request for deletion|itemid={qid}|reason={msg}}}}} --~~~~'.format(qid=item.getID(), msg=msg)
page.save(comment=u'[[Wikidata:Bots|Bot]]: nominating [[{qid}]] for deletion'.format(qid=item.getID()), minor=False, botflag=True)
pywikibot.output(u'\03{{lightgreen}}{item} successfully nominated for deletion'.format(item=item))
return True
else:
item.delete(reason=(msg if msg else u'Merged with [[{qid}]] by [[User:{by}|{by}]]'.format(qid=other.getID(), by=by)))
pywikibot.output(u'\03{{lightgreen}}{item} successfully deleted'.format(item=item))
return True
示例9: check_protection_level
def check_protection_level(operation, level, levels, default=None):
"""Check if the protection level is valid or asks if necessary.
@return a valid protection level
@rtype string
"""
if level not in levels:
first_char = []
default_char = None
num = 1
for level in levels:
for c in level:
if c not in first_char:
first_char.append(c)
break
else:
first_char.append(unicode(num))
num += 1
if level == default:
default_char = first_char[-1]
choice = pywikibot.inputChoice('Choice a protection level to %s:'
% operation, levels, first_char,
default=default_char)
return levels[first_char.index(choice)]
else:
return level
示例10: get_dest
def get_dest(self):
self.dest = u'%s-core.%s' % tuple(self.source.rsplit(u'.', 1))
if not self.warnonly and pywikibot.inputChoice(
u'Destination file is %s.' % self.dest,
['Yes', 'No'], ['y', 'n'], 'y') == 'n':
pywikibot.output('Quitting...')
exit()
示例11: save
def save(self, page, newText):
"""
Saves the page to the wiki, if the user accepts the changes made.
"""
pywikibot.showDiff(page.get(), newText)
if not self.always:
choice = pywikibot.inputChoice(
u'Do you want to accept these changes?',
['Yes', 'No', 'Always yes'], 'yNa', 'Y')
if choice == 'n':
return
elif choice == 'a':
self.always = True
page.text = newText
if self.always:
try:
page.save(self.comment)
except pywikibot.EditConflict:
pywikibot.output(u'Skipping %s because of edit conflict'
% (page.title(),))
except pywikibot.SpamfilterError as e:
pywikibot.output(
u'Cannot change %s because of blacklist entry %s'
% (page.title(), e.url))
except pywikibot.LockedPage:
pywikibot.output(u'Skipping %s (locked page)' % (page.title(),))
else:
# Save the page in the background. No need to catch exceptions.
page.save(self.comment, async=True)
示例12: wait_completion
def wait_completion(self):
"""Pending threads finish."""
def remaining():
remainingItems = self.pool.qsize() - 1
# -1 because we added a None element to stop the queue
remainingSeconds = ltime.td(seconds=remainingItems)
return (remainingItems, remainingSeconds)
self.pool.put((None, [], {}))
if self.pool.qsize() > 1:
pywikibot.output(u'Waiting for %i items to be put. Estimated time remaining: %s'
% remaining())
while(self.thread.isAlive()):
try:
self.thread.join(1)
except KeyboardInterrupt:
answer = pywikibot.inputChoice(u"""\
There are %i items remaining in the queue. Estimated time remaining: %s
Really exit?"""
% remaining(),
['yes', 'no'], ['y', 'N'], 'N')
if answer == 'y':
return
示例13: put_page
def put_page(self, page, new):
""" Print diffs between orginal and new (text), put new text for page
"""
pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
% page.title())
pywikibot.showDiff(page.get(), new)
if not self.acceptall:
choice = pywikibot.inputChoice(u'Do you want to accept ' +
u'these changes?',
['Yes', 'No', 'All'],
['y', 'N', 'a'], 'N')
if choice == 'a':
self.acceptall = True
if choice == 'y':
page.text = new
page.save(self.msg, async=True)
if self.acceptall:
try:
page.text = new
page.save(self.msg)
except pywikibot.EditConflict:
pywikibot.output(u'Skipping %s because of edit conflict'
% (page.title(),))
except pywikibot.SpamfilterError as e:
pywikibot.output(
u'Cannot change %s because of blacklist entry %s'
% (page.title(), e.url))
except pywikibot.PageNotSaved as error:
pywikibot.error(u'putting page: %s' % (error.args,))
except pywikibot.LockedPage:
pywikibot.output(u'Skipping %s (locked page)'
% (page.title(),))
except pywikibot.ServerError as e:
pywikibot.output(u'Server Error : %s' % e)
示例14: handleNextLink
def handleNextLink(self, 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 self.pageToUnlink.site.isInterwikiLink(match.group('title')) \
or match.group('section'):
return text, False
linkedPage = pywikibot.Page(self.pageToUnlink.site,
match.group('title'))
# Check whether the link found is to the current page itself.
if linkedPage != self.pageToUnlink:
# not a self-link
return text, False
else:
# at the beginning of the link, start red color.
# at the end of the link, reset the color to default
if self.getOption('always'):
choice = 'a'
else:
pywikibot.output(
text[max(0, match.start() - context):match.start()]
+ '\03{lightred}' + text[match.start():match.end()]
+ '\03{default}' + text[match.end():match.end() + context])
choice = pywikibot.inputChoice(
u'\nWhat shall be done with this link?\n',
['unlink', 'skip', 'edit', 'more context',
'unlink all', 'quit'],
['U', 's', 'e', 'm', 'a', 'q'], 'u')
pywikibot.output(u'')
if choice == 's':
# skip this link
return text, False
elif choice == 'e':
editor = TextEditor()
newText = editor.edit(text, jumpIndex=match.start())
# if user didn't press Cancel
if newText:
return newText, True
else:
return text, True
elif choice == 'm':
# show more context by recursive self-call
return self.handleNextLink(text, match,
context=context + 100)
elif choice == 'a':
self.options['always'] = True
elif choice == 'q':
self.quit()
new = match.group('label') or match.group('title')
new += match.group('linktrail')
return text[:match.start()] + new + text[match.end():], False
示例15: save
def save(self, text, page, comment=None, minorEdit=True,
botflag=True):
# only save if something was changed
if text != page.get():
# 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} <<<"
% page.title())
# show what was changed
pywikibot.showDiff(page.get(), text)
pywikibot.output(u'Comment: %s' % comment)
if not self.dry:
choice = pywikibot.inputChoice(
u'Do you want to accept these changes?',
['Yes', 'No'], ['y', 'N'], 'N')
if choice == 'y':
try:
page.text = text
# Save the page
page.save(comment=comment or self.comment,
minor=minorEdit, botflag=botflag)
except pywikibot.LockedPage:
pywikibot.output(u"Page %s is locked; skipping."
% page.title(asLink=True))
except pywikibot.EditConflict:
pywikibot.output(
u'Skipping %s because of edit conflict'
% (page.title()))
except pywikibot.SpamfilterError as error:
pywikibot.output(
u'Cannot change %s because of spam blacklist entry %s'
% (page.title(), error.url))
else:
return True
return False