本文整理汇总了Python中pywikibot.input_choice函数的典型用法代码示例。如果您正苦于以下问题:Python input_choice函数的具体用法?Python input_choice怎么用?Python input_choice使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了input_choice函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_or_create_page
def update_or_create_page(self, old_page, new_text):
"""
Reads the current text of page old_page,
compare it with new_text, prompts the user,
and uploads the page
"""
# Read the original content
old_text = old_page.get()
# Give the user some context
if old_text != new_text:
pywikibot.output(new_text)
pywikibot.showDiff(old_text, new_text)
# Get a decision
prompt = u'Modify this page ?'
# Did anything change ?
if old_text == new_text:
pywikibot.output(u'No changes necessary to %s' % old_page.title());
else:
if not self.acceptall:
choice = pywikibot.input_choice(u'Do you want to accept these changes?', [('Yes', 'Y'), ('No', 'n'), ('All', 'a')], 'N')
if choice == 'a':
self.acceptall = True
if self.acceptall or choice == 'y':
# Write out the new version
old_page.put(new_text, summary)
示例2: check_protection_level
def check_protection_level(operation, level, levels, default=None):
"""Check if the protection level is valid or ask 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(str(num))
num += 1
if level == default:
default_char = first_char[-1]
choice = pywikibot.input_choice('Choice a protection level to %s:'
% operation, zip(levels, first_char),
default=default_char)
return levels[first_char.index(choice)]
else:
return level
示例3: treat
def treat(self, page):
if not page.exists():
return
if page.isRedirectPage():
page = page.getRedirectTarget()
page_t = page.title()
self.current_page = page
if self.getOption('titlecase'):
page_cap = pywikibot.Page(page.site, page_t.title())
else:
page_cap = pywikibot.Page(page.site, page_t.capitalize())
if page_cap.exists():
pywikibot.output(u'%s already exists, skipping...\n'
% page_cap.title(asLink=True))
else:
pywikibot.output(u'%s doesn\'t exist'
% page_cap.title(asLink=True))
if not self.getOption('always'):
choice = pywikibot.input_choice(
u'Do you want to create a redirect?',
[('Yes', 'y'), ('No', 'n'), ('All', 'a')], 'n')
if choice == 'a':
self.options['always'] = True
if self.getOption('always') or choice == 'y':
comment = i18n.twtranslate(
page.site,
'capitalize_redirects-create-redirect',
{'to': page_t})
page_cap.text = u"#%s %s" % (page.site.redirect(),
page.title(asLink=True,
textlink=True))
try:
page_cap.save(comment)
except:
pywikibot.output(u"An error occurred, skipping...")
示例4: treat_page
def treat_page(self):
"""Capitalize redirects of the current page."""
page_t = self.current_page.title()
site = self.current_page.site
if self.getOption('titlecase'):
page_cap = pywikibot.Page(site, page_t.title())
else:
page_cap = pywikibot.Page(site, page_t.capitalize())
if page_cap.exists():
pywikibot.output(u'%s already exists, skipping...\n'
% page_cap.title(asLink=True))
else:
pywikibot.output(u'%s doesn\'t exist'
% page_cap.title(asLink=True))
if not self.getOption('always'):
choice = pywikibot.input_choice(
u'Do you want to create a redirect?',
[('Yes', 'y'), ('No', 'n'), ('All', 'a')], 'n')
if choice == 'a':
self.options['always'] = True
if self.getOption('always') or choice == 'y':
comment = i18n.twtranslate(
site,
'capitalize_redirects-create-redirect',
{'to': page_t})
page_cap.set_redirect_target(self.current_page, create=True,
summary=comment)
示例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: handleNextLink
def handleNextLink(self, text, match, context=100):
"""
Return 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.input_choice(
u'\nWhat shall be done with this link?\n',
[('unlink', 'u'), ('skip', 's'), ('edit', 'e'),
('more context', 'm'), ('unlink all', 'a')], '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
new = match.group('label') or match.group('title')
new += match.group('linktrail')
return text[:match.start()] + new + text[match.end():], False
示例7: reportBadAccount
def reportBadAccount(self, name=None, final=False):
# Queue process
if name:
if globalvar.confirm:
answer = pywikibot.input_choice(
"%s may have an unwanted username, do you want to report " "this user?" % name,
[("Yes", "y"), ("No", "n"), ("All", "a")],
"n",
automatic_quit=False,
)
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("%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, i18n.translate(self.site, report_page))
if rep_page.exists():
text_get = rep_page.get()
else:
text_get = "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("%s is already in the report page." % username)
else:
# Adding the log.
rep_text += i18n.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, summary=com, force=True, minorEdit=True)
showStatus(5)
pywikibot.output("Reported")
self.BAQueue = list()
else:
return True
示例8: _call_input_choice
def _call_input_choice(self):
rv = pywikibot.input_choice(
"question", (("answer 1", "A"), ("answer 2", "N"), ("answer 3", "S")), "A", automatic_quit=False
)
self.assertEqual(newstdout.getvalue(), "")
self.assertIsInstance(rv, unicode)
return rv
示例9: PickTarget
def PickTarget(self, title, original, candidates):
"""Pick target from candidates."""
if len(candidates) == 0:
return
if len(candidates) == 1:
return candidates[0]
pagesDontExist = []
pagesRedir = {}
pagesExist = []
for newTitle in candidates:
dst = self.Page(newTitle)
if not dst.exists():
pagesDontExist.append(newTitle)
elif dst.isRedirectPage():
pagesRedir[newTitle] = dst.getRedirectTarget().title()
else:
pagesExist.append(newTitle)
if len(pagesExist) == 1:
return pagesExist[0]
elif len(pagesExist) == 0 and len(pagesRedir) > 0:
if len(pagesRedir) == 1:
return list(pagesRedir.keys())[0]
t = None
for v in pagesRedir.values():
if not t:
t = v # first item
elif t != v:
break
else:
# all redirects point to the same target
# pick the first one, doesn't matter what it is
return list(pagesRedir.keys())[0]
if not self.autonomous:
pywikibot.output(u'Could not auto-decide for page %s. Which link '
u'should be chosen?' % self.MakeLink(title, False))
pywikibot.output(u'Original title: ', newline=False)
self.ColorCodeWord(original + "\n", True)
count = 1
for t in candidates:
if t in pagesDontExist:
msg = u'missing'
elif t in pagesRedir:
msg = u'Redirect to ' + pagesRedir[t]
else:
msg = u'page exists'
self.ColorCodeWord(u' %d: %s (%s)\n' % (count, t, msg), True)
count += 1
answers = [('skip', 's')] + [(str(i), i) for i in range(1, count)]
choice = pywikibot.input_choice(u'Which link to choose?', answers)
if choice != 's':
return candidates[int(choice) - 1]
示例10: showQuest
def showQuest(page):
"""Ask for an editor and invoke it."""
quest = pywikibot.input_choice(
u'Do you want to open the page?',
[('with browser', 'b'), ('with gui', 'g'), ('no', 'n')], 'n',
automatic_quit=False)
if quest == 'b':
webbrowser.open('%s?redirect=no' % page.full_url())
elif quest == 'g':
from pywikibot import editor as editarticle
editor = editarticle.TextEditor()
editor.edit(page.text)
示例11: getRecentEdits
def getRecentEdits(userName,timestamp):
recentEdits = site.usercontribs(user=userName,top_only=True,end=timestamp)
print u"Number of recent edits for " + userName + " : " + str(len(list(recentEdits)))
acceptAll = False
for edit in recentEdits:
page = pywikibot.Page(site,edit[u'title'])
hist = page.getVersionHistory()
previous_revision = ()
for hist_entry in hist:
#On renvoit la revision précédant celle(s) de <userName>
if hist_entry.user != userName:
previous_revision = hist_entry.revid, hist_entry.user
break
oldVersion = page.getOldVersion(previous_revision[0])
# Affichage du diff
pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
% page.title())
pywikibot.showDiff(page.text,oldVersion)
summary = u"Révocation massive des modifications de %s (retour à la version de %s)" %(userName,previous_revision[1])
if not acceptAll:
choice = pywikibot.input_choice(u'Do you want to accept these changes?',
[('Yes', 'y'), ('No', 'n'), ('All', 'a')], 'N')
if choice == 'a':
acceptAll = True
elif choice == 'n':
continue
if acceptAll or choice == 'y':
try:
page.text = oldVersion
page.save(summary)
except pywikibot.EditConflict:
pywikibot.output(u"Skipping %s because of edit conflict"
% (page.title(),))
except pywikibot.SpamfilterError, e:
pywikibot.output(u"Cannot change %s because of blacklist entry %s"
% (page.title(), e.url))
except pywikibot.PageNotSaved, error:
pywikibot.output(u"Error putting page: %s"
% (error.args,))
示例12: treat
def treat(self, page):
"""Re-directing process.
Check if pages are in the given form Something, State, and
if so, create a redirect from Something, ST..
"""
for sn in self.abbrev:
R = re.compile(r', %s$' % sn)
if R.search(page.title()):
pl = pywikibot.Page(self.site, page.title().replace(sn,
self.abbrev[sn]))
# A bit hacking here - the real work is done in the
# 'except pywikibot.NoPage' part rather than the 'try'.
try:
pl.get(get_redirect=True)
goal = pl.getRedirectTarget().title()
if pywikibot.Page(self.site, goal).exists():
pywikibot.output(
u"Not creating %s - redirect already exists."
% goal)
else:
pywikibot.warning(
u"%s already exists but redirects elsewhere!"
% goal)
except pywikibot.IsNotRedirectPage:
pywikibot.warning(
u"Page %s already exists and is not a redirect "
u"Please check page!"
% pl.title())
except pywikibot.NoPage:
change = ''
if page.isRedirectPage():
p2 = page.getRedirectTarget()
pywikibot.output(
u'Note: goal page is redirect.\nCreating redirect '
u'to "%s" to avoid double redirect.' % p2.title())
else:
p2 = page
if self.force:
change = 'y'
else:
change = pywikibot.input_choice(
u'Create redirect %s?' % pl.title(),
(('yes', 'y'), ('no', 'n')))
if change == 'y':
pl.set_redirect_target(
p2, create=True,
summary=i18n.twtranslate(self.site,
'states_redirect-comment'))
示例13: _call_input_choice
def _call_input_choice(self):
rv = pywikibot.input_choice(
'question',
(('answer 1', u'A'),
('answer 2', u'N'),
('answer 3', u'S')),
u'A',
automatic_quit=False)
self.assertEqual(newstdout.getvalue(), '')
self.assertIsInstance(rv, unicode)
return rv
示例14: review_hunks
def review_hunks(self):
"""Review hunks."""
help_msg = ['y -> accept this hunk',
'n -> do not accept this hunk',
's -> do not accept this hunk and stop reviewing',
'a -> accept this hunk and all other pending',
'r -> review later',
'h -> help',
]
question = 'Accept this hunk?'
answers = [('yes', 'y'), ('no', 'n'), ('stop', 's'), ('all', 'a'),
('review', 'r'), ('help', 'h')]
actions = {'y': Hunk.APPR,
'n': Hunk.NOT_APPR,
's': Hunk.NOT_APPR,
'a': Hunk.APPR,
'r': Hunk.PENDING,
}
pending = [h for h in self.hunks if h.reviewed == h.PENDING]
while pending:
hunk = pending.pop(0)
pywikibot.output(hunk.header + hunk.diff_text)
choice = pywikibot.input_choice(question, answers, default='r',
automatic_quit=False)
if choice in actions.keys():
hunk.reviewed = actions[choice]
if choice == 's':
while pending:
hunk = pending.pop(0)
hunk.reviewed = hunk.NOT_APPR
break
elif choice == 'a':
while pending:
hunk = pending.pop(0)
hunk.reviewed = hunk.APPR
break
elif choice == 'h':
pywikibot.output(u'\03{purple}%s\03{default}' % u'\n'.join(help_msg))
pending.insert(0, hunk)
elif choice == 'r':
pending.append(hunk)
return
示例15: showQuest
def showQuest(page):
"""Ask for an editor and invoke it."""
quest = pywikibot.input_choice(
"Do you want to open the page?",
[("with browser", "b"), ("with gui", "g"), ("no", "n")],
"n",
automatic_quit=False,
)
if quest == "b":
webbrowser.open("%s?redirect=no" % page.full_url())
elif quest == "g":
from pywikibot import editor as editarticle
editor = editarticle.TextEditor()
editor.edit(page.text)