本文整理汇总了Python中pywikibot.stdout函数的典型用法代码示例。如果您正苦于以下问题:Python stdout函数的具体用法?Python stdout怎么用?Python stdout使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了stdout函数的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
"""
all = False
new = False
sysop = False
for arg in pywikibot.handle_args(args):
if arg in ('-all', '-update'):
all = True
elif arg == '-new':
new = True
elif arg == '-sysop':
sysop = True
if all:
refresh_all(sysop=sysop)
elif new:
refresh_new(sysop=sysop)
else:
site = pywikibot.Site()
watchlist = refresh(site, sysop=sysop)
pywikibot.output(u'{0:d} pages in the watchlist.'.format(len(watchlist)))
for page in watchlist:
try:
pywikibot.stdout(page.title())
except pywikibot.InvalidTitle:
pywikibot.exception()
示例2: main
def main(*args):
gen = None
notitle = False
page_get = False
# Process global args and prepare generator args parser
local_args = pywikibot.handleArgs(*args)
genFactory = GeneratorFactory()
for arg in local_args:
if arg == '-notitle':
notitle = True
elif arg == '-get':
page_get = True
else:
genFactory.handleArg(arg)
gen = genFactory.getCombinedGenerator()
if gen:
for i, page in enumerate(gen, start=1):
if not notitle:
pywikibot.stdout("%4d: %s" % (i, page.title()))
if page_get:
# TODO: catch exceptions
pywikibot.output(page.text, toStdout=True)
else:
pywikibot.showHelp()
示例3: login
def login(self, retry=False, force=False):
"""
Attempt to log into the server.
@param retry: infinitely retry if exception occurs during authentication.
@type retry: bool
@param force: force to re-authenticate
@type force: bool
"""
if self.access_token is None or force:
pywikibot.output('Logging in to {site!s} via OAuth consumer {key!s}'.format(**{'key': self.consumer_token[0],
'site': self.site}))
consumer_token = mwoauth.ConsumerToken(self.consumer_token[0],
self.consumer_token[1])
handshaker = mwoauth.Handshaker(
self.site.base_url(self.site.path()), consumer_token)
try:
redirect, request_token = handshaker.initiate()
pywikibot.stdout('Authenticate via web browser..')
webbrowser.open(redirect)
pywikibot.stdout('If your web browser does not open '
'automatically, please point it to: %s'
% redirect)
request_qs = pywikibot.input('Response query string: ')
access_token = handshaker.complete(request_token,
request_qs)
self._access_token = (access_token.key, access_token.secret)
except Exception as e:
pywikibot.error(e)
if retry:
self.login(retry=True, force=force)
else:
pywikibot.output('Logged in to {site!s} via consumer {key!s}'.format(**{'key': self.consumer_token[0],
'site': self.site}))
示例4: main
def main(*args):
gen = None
notitle = False
fmt = '1'
outputlang = None
page_get = False
# Process global args and prepare generator args parser
local_args = pywikibot.handleArgs(*args)
genFactory = GeneratorFactory()
for arg in local_args:
if arg == '-notitle':
notitle = True
elif arg.startswith("-format:"):
fmt = arg[len("-format:"):]
fmt = fmt.replace(u'\\03{{', u'\03{{')
elif arg.startswith("-outputlang:"):
outputlang = arg[len("-outputlang:"):]
elif arg == '-get':
page_get = True
else:
genFactory.handleArg(arg)
gen = genFactory.getCombinedGenerator()
if gen:
for i, page in enumerate(gen, start=1):
if not notitle:
page_fmt = Formatter(page, outputlang)
pywikibot.stdout(page_fmt.output(num=i, fmt=fmt))
if page_get:
# TODO: catch exceptions
pywikibot.output(page.text, toStdout=True)
else:
pywikibot.showHelp()
示例5: main
def main(*args):
gen = None
fmt = "{num:4d} {page.title}"
genFactory = GeneratorFactory()
for arg in pywikibot.handleArgs(*args):
if arg.startswith("-format:"):
fmt = arg[len("-format:"):]
genFactory.handleArg(arg)
gen = genFactory.getCombinedGenerator()
if gen:
for i, page in enumerate(gen):
pywikibot.stdout(fmt.format(num=i, page=page))
else:
pywikibot.showHelp()
示例6: listTemplates
def listTemplates(cls, templates, namespaces):
"""
Display transcluded pages for a list of templates.
Displays each transcluded page in the given 'namespaces' for
each template given by 'templates' list.
@param templates: list of template names
@type templates: list
@param namespaces: list of namespace numbers
@type namespaces: list
"""
templateDict = cls.template_dict(templates, namespaces)
pywikibot.stdout('\nList of pages transcluding templates:')
for key in templates:
pywikibot.output(u'* %s' % key)
pywikibot.stdout('-' * 36)
total = 0
for key in templateDict:
for page in templateDict[key]:
pywikibot.stdout(page.title())
total += 1
pywikibot.output(u'Total page count: %d' % total)
pywikibot.stdout('Report generated on {0}'
''.format(datetime.datetime.utcnow().isoformat()))
示例7: main
def main(*args):
try:
gen = None
genFactory = GeneratorFactory()
for arg in pywikibot.handleArgs(*args):
genFactory.handleArg(arg)
gen = genFactory.getCombinedGenerator()
if gen:
for page in gen:
pywikibot.stdout(page.title())
else:
pywikibot.showHelp()
except Exception:
pywikibot.error("Fatal error", exc_info=True)
finally:
pywikibot.stopme()
示例8: countTemplates
def countTemplates(cls, templates, namespaces):
"""
Display number of transclusions for a list of templates.
Displays the number of transcluded page in the given 'namespaces' for
each template given by 'templates' list.
@param templates: list of template names
@type templates: list
@param namespaces: list of namespace numbers
@type namespaces: list
"""
FORMAT = '{0:<10}: {1:>5}'
templateDict = cls.template_dict(templates, namespaces)
pywikibot.stdout('\nNumber of transclusions per template')
pywikibot.stdout('-' * 36)
total = 0
for key in templateDict:
count = len(templateDict[key])
pywikibot.stdout(FORMAT.format(key, count))
total += count
pywikibot.stdout(FORMAT.format('TOTAL', total))
pywikibot.stdout('Report generated on {0}'
''.format(datetime.datetime.utcnow().isoformat()))
示例9: 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
notitle = False
fmt = '1'
outputlang = None
page_get = False
base_dir = None
encoding = config.textfile_encoding
page_target = None
overwrite = False
summary = 'listpages-save-list'
# Process global args and prepare generator args parser
local_args = pywikibot.handle_args(args)
genFactory = GeneratorFactory()
for arg in local_args:
if arg == '-notitle':
notitle = True
elif arg.startswith('-format:'):
fmt = arg[len('-format:'):]
fmt = fmt.replace(u'\\03{{', u'\03{{')
elif arg.startswith('-outputlang:'):
outputlang = arg[len('-outputlang:'):]
elif arg == '-get':
page_get = True
elif arg.startswith('-save'):
base_dir = arg.partition(':')[2] or '.'
elif arg.startswith('-encode:'):
encoding = arg.partition(':')[2]
elif arg.startswith('-put:'):
page_target = arg.partition(':')[2]
elif arg.startswith('-overwrite'):
overwrite = True
elif arg.startswith('-summary:'):
summary = arg.partition(':')[2]
else:
genFactory.handleArg(arg)
if base_dir:
base_dir = os.path.expanduser(base_dir)
if not os.path.isabs(base_dir):
base_dir = os.path.normpath(os.path.join(os.getcwd(), base_dir))
if not os.path.exists(base_dir):
pywikibot.output(u'Directory "{0!s}" does not exist.'.format(base_dir))
choice = pywikibot.input_yn(
u'Do you want to create it ("No" to continue without saving)?')
if choice:
os.makedirs(base_dir, mode=0o744)
else:
base_dir = None
elif not os.path.isdir(base_dir):
# base_dir is a file.
pywikibot.warning(u'Not a directory: "%s"\n'
u'Skipping saving ...'
% base_dir)
base_dir = None
if page_target:
site = pywikibot.Site()
page_target = pywikibot.Page(site, page_target)
if not overwrite and page_target.exists():
pywikibot.bot.suggest_help(
additional_text='Page "{0}" already exists.'.format(
page_target.title()))
return False
if re.match('^[a-z_-]+$', summary):
summary = i18n.twtranslate(site, summary)
gen = genFactory.getCombinedGenerator()
if gen:
i = 0
output_list = []
for i, page in enumerate(gen, start=1):
if not notitle:
page_fmt = Formatter(page, outputlang)
output_list += [page_fmt.output(num=i, fmt=fmt)]
pywikibot.stdout(output_list[-1])
if page_get:
try:
pywikibot.stdout(page.text)
except pywikibot.Error as err:
pywikibot.output(err)
if base_dir:
filename = os.path.join(base_dir, page.title(as_filename=True))
pywikibot.output(u'Saving {0!s} to {1!s}'.format(page.title(), filename))
with open(filename, mode='wb') as f:
f.write(page.text.encode(encoding))
pywikibot.output(u"{0:d} page(s) found".format(i))
if page_target:
page_target.text = '\n'.join(output_list)
#.........这里部分代码省略.........
示例10: showHelp
def showHelp(name=""):
# argument, if given, is ignored
modname = calledModuleName()
if not modname:
try:
modname = sys.modules['__main__'].main.__module__
except NameError:
modname = "no_module"
globalHelp = u'''
Global arguments available for all bots:
-dir:PATH Read the bot's configuration data from directory given by
PATH, instead of from the default directory.
-lang:xx Set the language of the wiki you want to work on, overriding
the configuration in user-config.py. xx should be the
language code.
-family:xyz Set the family of the wiki you want to work on, e.g.
wikipedia, wiktionary, wikitravel, ...
This will override the configuration in user-config.py.
-user:xyz Log in as user 'xyz' instead of the default username.
-daemonize:xyz Immediately return control to the terminal and redirect
stdout and stderr to xyz (only use for bots that require
no input from stdin).
-help Show this help text.
-log Enable the logfile, using the default filename
'%s-bot.log'
Logs will be stored in the logs subdirectory.
-log:xyz Enable the logfile, using 'xyz' as the filename.
-nolog Disable the logfile (if it is enabled by default).
-maxlag Sets a new maxlag parameter to a number of seconds. Defer bot
edits during periods of database server lag. Default is set by
config.py
-putthrottle:n Set the minimum time (in seconds) the bot will wait between
-pt:n saving pages.
-put_throttle:n
-debug:item Enable the logfile and include extensive debugging data
-debug for component "item" (for all components if the second form
is used).
-verbose Have the bot provide additional console output that may be
-v useful in debugging.
-cosmeticchanges Toggles the cosmetic_changes setting made in config.py or
-cc user_config.py to its inverse and overrules it. All other
settings and restrictions are untouched.
-simulate Disables writing to the server. Useful for testing and
debugging of new code (if given, doesn't do any real
changes, but only shows what would have been changed).
-<config var>:n You may use all given numeric config variables as option and
modify it with command line.
''' % modname
try:
module = __import__('%s' % modname)
helpText = module.__doc__.decode('utf-8')
if hasattr(module, 'docuReplacements'):
for key, value in module.docuReplacements.items():
helpText = helpText.replace(key, value.strip('\n\r'))
pywikibot.stdout(helpText) # output to STDOUT
except Exception:
if modname:
pywikibot.stdout(u'Sorry, no help available for %s' % modname)
pywikibot.log('showHelp:', exc_info=True)
pywikibot.stdout(globalHelp)
示例11: main
def main(*args):
"""
Process command line arguments and perform task.
If args is an empty list, sys.argv is used.
@param args: command line arguments
@type args: list of unicode
"""
pywikibot.handle_args(args)
if config.family != 'wikipedia' or config.mylang != 'en':
pywikibot.warning('CFD does work only on the English Wikipedia.')
return
page = pywikibot.Page(pywikibot.Site(), cfdPage)
# Variable declarations
day = 'None'
mode = 'None'
summary = ''
action_summary = ''
robot = None
m = ReCheck()
for line in page.text.split("\n"):
if nobots.search(line):
# NO BOTS!!!
pass
elif example.search(line):
# Example line
pass
elif speedymode.search(line):
mode = "Speedy"
day = "None"
elif movemode.search(line):
mode = "Move"
day = "None"
elif emptymode.search(line):
mode = "Empty"
day = "None"
elif deletemode.search(line):
mode = "Delete"
day = "None"
elif maintenance.search(line):
# It's probably best not to try to handle these in an automated fashion.
mode = "None"
day = "None"
elif m.check(dateheader, line):
day = m.result.group(1)
pywikibot.output("Found day header: %s" % day)
elif m.check(movecat, line):
src = m.result.group(1)
dest = m.result.group(2)
thisDay = findDay(src, day)
if mode == "Move" and thisDay != "None":
summary = (
'Robot - Moving category ' + src + ' to [[:Category:' +
dest + ']] per [[WP:CFD|CFD]] at ' + thisDay + '.')
action_summary = 'Robot - Result of [[WP:CFD|CFD]] at ' + thisDay + '.'
elif mode == "Speedy":
summary = (
'Robot - Speedily moving category ' + src +
' to [[:Category:' + dest + ']] per [[WP:CFDS|CFDS]].')
action_summary = 'Robot - Speedily moved per [[WP:CFDS|CFDS]].'
else:
continue
# If the category is redirect, we do NOT want to move articles to
# it. The safest thing to do here is abort and wait for human
# intervention.
destpage = pywikibot.Page(page.site, dest, ns=14)
if destpage.isCategoryRedirect():
summary = 'CANCELED. Destination is redirect: ' + summary
pywikibot.stdout(summary)
robot = None
else:
deletion_comment_same = (
CategoryMoveBot.DELETION_COMMENT_SAME_AS_EDIT_COMMENT)
robot = CategoryMoveBot(oldcat=src, newcat=dest, batch=True,
comment=summary, inplace=True,
move_oldcat=True, delete_oldcat=True,
deletion_comment=deletion_comment_same,
move_comment=action_summary)
elif m.check(deletecat, line):
src = m.result.group(1)
# I currently don't see any reason to handle these two cases
# separately, though if are guaranteed that the category in the
# "Delete" case is empty, it might be easier to call delete.py on
# it.
thisDay = findDay(src, day)
if (mode == "Empty" or mode == "Delete") and thisDay != "None":
summary = (
'Robot - Removing category {0} per [[WP:CFD|CFD]] '
'at {1}.'.format(src, thisDay))
action_summary = 'Robot - Result of [[WP:CFD|CFD]] at ' + thisDay + '.'
else:
continue
robot = CategoryMoveBot(oldcat=src, batch=True, comment=summary,
deletion_comment=action_summary,
inplace=True)
#.........这里部分代码省略.........
示例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
"""
gen = None
notitle = False
fmt = '1'
outputlang = None
page_get = False
base_dir = None
encoding = config.textfile_encoding
# Process global args and prepare generator args parser
local_args = pywikibot.handle_args(args)
genFactory = GeneratorFactory()
for arg in local_args:
if arg == '-notitle':
notitle = True
elif arg.startswith('-format:'):
fmt = arg[len('-format:'):]
fmt = fmt.replace(u'\\03{{', u'\03{{')
elif arg.startswith('-outputlang:'):
outputlang = arg[len('-outputlang:'):]
elif arg == '-get':
page_get = True
elif arg.startswith('-save'):
base_dir = arg.partition(':')[2] or '.'
elif arg.startswith('-encode:'):
encoding = arg.partition(':')[2]
else:
genFactory.handleArg(arg)
if base_dir:
base_dir = os.path.expanduser(base_dir)
if not os.path.isabs(base_dir):
base_dir = os.path.normpath(os.path.join(os.getcwd(), base_dir))
if not os.path.exists(base_dir):
pywikibot.output(u'Directory "%s" does not exist.' % base_dir)
choice = pywikibot.input_yn(
u'Do you want to create it ("No" to continue without saving)?')
if choice:
os.makedirs(base_dir, mode=0o744)
else:
base_dir = None
elif not os.path.isdir(base_dir):
# base_dir is a file.
pywikibot.warning(u'Not a directory: "%s"\n'
u'Skipping saving ...'
% base_dir)
base_dir = None
gen = genFactory.getCombinedGenerator()
if gen:
i = 0
for i, page in enumerate(gen, start=1):
if not notitle:
page_fmt = Formatter(page, outputlang)
pywikibot.stdout(page_fmt.output(num=i, fmt=fmt))
if page_get:
try:
pywikibot.output(page.text, toStdout=True)
except pywikibot.Error as err:
pywikibot.output(err)
if base_dir:
filename = os.path.join(base_dir, page.title(as_filename=True))
pywikibot.output(u'Saving %s to %s' % (page.title(), filename))
with open(filename, mode='wb') as f:
f.write(page.text.encode(encoding))
pywikibot.output(u"%i page(s) found" % i)
else:
pywikibot.showHelp()
示例13: test_stdout
def test_stdout(self):
pywikibot.stdout('output')
self.assertEqual(newstdout.getvalue(), 'output\n')
self.assertEqual(newstderr.getvalue(), '')
示例14: httpError
def httpError(self, err_num, link, pagetitleaslink):
"""Log HTTP Error."""
pywikibot.stdout('HTTP error ({0}) for {1} on {2}'
''.format(err_num, link, pagetitleaslink))
示例15: main
def main(*args):
"""
Process command line arguments and perform task.
If args is an empty list, sys.argv is used.
@param args: command line arguments
@type args: list of unicode
"""
cfd_page = DEFAULT_CFD_PAGE
local_args = pywikibot.handle_args(args)
for arg in local_args:
if arg.startswith('-page'):
if len(arg) == len('-page'):
cfd_page = pywikibot.input('Enter the CFD working page to use:')
else:
cfd_page = arg[len('-page:'):]
page = pywikibot.Page(pywikibot.Site(), cfd_page)
try:
page.get()
except pywikibot.NoPage:
pywikibot.error(
'CFD working page "{0}" does not exist!'.format(cfd_page))
sys.exit(1)
# Variable declarations
day = 'None'
mode = 'None'
summary = ''
action_summary = ''
robot = None
m = ReCheck()
for line in page.text.split("\n"):
if nobots.search(line):
# NO BOTS!!!
pass
elif example.search(line):
# Example line
pass
elif speedymode.search(line):
mode = "Speedy"
day = "None"
elif movemode.search(line):
mode = "Move"
day = "None"
elif emptymode.search(line):
mode = "Empty"
day = "None"
elif deletemode.search(line):
mode = "Delete"
day = "None"
elif maintenance.search(line):
# It's probably best not to try to handle these in an automated fashion.
mode = "None"
day = "None"
elif m.check(dateheader, line):
day = m.result.group(1)
pywikibot.output("Found day header: %s" % day)
elif m.check(movecat, line):
src = m.result.group(1)
dest = m.result.group(2)
thisDay = findDay(src, day)
if mode == "Move" and thisDay != "None":
summary = (
'Robot - Moving category ' + src + ' to [[:Category:' +
dest + ']] per [[WP:CFD|CFD]] at ' + thisDay + '.')
action_summary = 'Robot - Result of [[WP:CFD|CFD]] at ' + thisDay + '.'
elif mode == "Speedy":
summary = (
'Robot - Speedily moving category ' + src +
' to [[:Category:' + dest + ']] per [[WP:CFDS|CFDS]].')
action_summary = 'Robot - Speedily moved per [[WP:CFDS|CFDS]].'
else:
continue
# If the category is redirect, we do NOT want to move articles to
# it. The safest thing to do here is abort and wait for human
# intervention.
destpage = pywikibot.Page(page.site, dest, ns=14)
if destpage.isCategoryRedirect():
summary = 'CANCELED. Destination is redirect: ' + summary
pywikibot.stdout(summary)
robot = None
else:
deletion_comment_same = (
CategoryMoveBot.DELETION_COMMENT_SAME_AS_EDIT_COMMENT)
robot = CategoryMoveBot(oldcat=src, newcat=dest, batch=True,
comment=summary, inplace=True,
move_oldcat=True, delete_oldcat=True,
deletion_comment=deletion_comment_same,
move_comment=action_summary)
elif m.check(deletecat, line):
src = m.result.group(1)
# I currently don't see any reason to handle these two cases
# separately, though if are guaranteed that the category in the
# "Delete" case is empty, it might be easier to call delete.py on
# it.
thisDay = findDay(src, day)
#.........这里部分代码省略.........