本文整理汇总了Python中pywikibot.exception函数的典型用法代码示例。如果您正苦于以下问题:Python exception函数的具体用法?Python exception怎么用?Python exception使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了exception函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: run
def run(self):
"""Process all pages in generator."""
if not hasattr(self, 'generator'):
raise NotImplementedError('Variable %s.generator not set.'
% self.__class__.__name__)
treat_missing_item = hasattr(self, 'treat_missing_item')
try:
for page in self.generator:
if not page.exists():
pywikibot.output('%s doesn\'t exist.' % page)
try:
item = pywikibot.ItemPage.fromPage(page)
except pywikibot.NoPage:
item = None
if not item:
if not treat_missing_item:
pywikibot.output(
'%s doesn\'t have a wikidata item.' % page)
#TODO FIXME: Add an option to create the item
continue
self.treat(page, item)
except QuitKeyboardInterrupt:
pywikibot.output('\nUser quit %s bot run...' %
self.__class__.__name__)
except KeyboardInterrupt:
if config.verbose_output:
raise
else:
pywikibot.output('\nKeyboardInterrupt during %s bot run...' %
self.__class__.__name__)
except Exception as e:
pywikibot.exception(msg=e, tb=True)
开发者ID:gitter-badger,项目名称:pywikibot,代码行数:34,代码来源:bot.py
示例2: revert
def revert(self, item):
history = pywikibot.Page(self.site, item['title']).fullVersionHistory(
total=2, rollback=self.rollback)
if len(history) > 1:
rev = history[1]
else:
return False
comment = i18n.twtranslate(pywikibot.Site(), 'revertbot-revert', {'revid': rev[0], 'author': rev[2], 'timestamp': rev[1]})
if self.comment:
comment += ': ' + self.comment
page = pywikibot.Page(self.site, item['title'])
pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
% page.title(asLink=True, forceInterwiki=True,
textlink=True))
if not self.rollback:
old = page.text
page.text = rev[3]
pywikibot.showDiff(old, page.text)
page.save(comment)
return comment
try:
pywikibot.data.api.Request(action="rollback", title=page.title(), user=self.user,
token=rev[4], markbot=1).submit()
except pywikibot.data.api.APIError as e:
if e.code == 'badtoken':
pywikibot.error("There was an API token error rollbacking the edit")
else:
pywikibot.exception()
return False
return u"The edit(s) made in %s by %s was rollbacked" % (page.title(), self.user)
开发者ID:donkaban,项目名称:pywiki-bot,代码行数:30,代码来源:revertbot.py
示例3: 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()
开发者ID:runt18,项目名称:pywikibot-core,代码行数:32,代码来源:watchlist.py
示例4: getPDFTitle
def getPDFTitle(self, ref, f):
"""Use pdfinfo to retrieve title from a PDF.
FIXME: Unix-only, I'm afraid.
"""
pywikibot.output(u'PDF file.')
fd, infile = tempfile.mkstemp()
urlobj = os.fdopen(fd, 'w+')
urlobj.write(f.content)
try:
pdfinfo_out = subprocess.Popen([r"pdfinfo", "/dev/stdin"],
stdin=urlobj, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=False).communicate()[0]
for aline in pdfinfo_out.splitlines():
if aline.lower().startswith('title'):
ref.title = aline.split(None)[1:]
ref.title = ' '.join(ref.title)
if ref.title != '':
pywikibot.output(u'title: %s' % ref.title)
pywikibot.output(u'PDF done.')
except ValueError:
pywikibot.output(u'pdfinfo value error.')
except OSError:
pywikibot.output(u'pdfinfo OS error.')
except Exception: # Ignore errors
pywikibot.output(u'PDF processing error.')
pywikibot.exception()
finally:
urlobj.close()
os.unlink(infile)
开发者ID:magul,项目名称:pywikibot-core,代码行数:33,代码来源:reflinks.py
示例5: revert
def revert(self, item):
history = pywikibot.Page(self.site, item["title"]).fullVersionHistory(total=2, rollback=self.rollback)
if len(history) > 1:
rev = history[1]
else:
return False
comment = i18n.twtranslate(
pywikibot.Site(), "revertbot-revert", {"revid": rev[0], "author": rev[2], "timestamp": rev[1]}
)
if self.comment:
comment += ": " + self.comment
page = pywikibot.Page(self.site, item["title"])
pywikibot.output(
"\n\n>>> \03{lightpurple}%s\03{default} <<<" % page.title(asLink=True, forceInterwiki=True, textlink=True)
)
if not self.rollback:
old = page.text
page.text = rev[3]
pywikibot.showDiff(old, page.text)
page.save(comment)
return comment
try:
pywikibot.data.api.Request(
self.site,
parameters={"action": "rollback", "title": page, "user": self.user, "token": rev[4], "markbot": True},
).submit()
except pywikibot.data.api.APIError as e:
if e.code == "badtoken":
pywikibot.error("There was an API token error rollbacking the edit")
else:
pywikibot.exception()
return False
return "The edit(s) made in %s by %s was rollbacked" % (page.title(), self.user)
开发者ID:happy5214,项目名称:pywikibot-core,代码行数:33,代码来源:revertbot.py
示例6: main
def main():
local_args = pywikibot.handleArgs()
cache_paths = None
delete = False
command = None
for arg in local_args:
if command == '':
command = arg
elif arg == '-delete':
delete = True
elif arg == '-password':
command = 'has_password(entry)'
elif arg == '-c':
if command:
pywikibot.error('Only one command may be executed.')
exit(1)
command = ''
else:
if not cache_paths:
cache_paths = [arg]
else:
cache_paths.append(arg)
func = None
if not cache_paths:
cache_paths = ['apicache', 'tests/apicache']
# Also process the base directory, if it isnt the current directory
if os.path.abspath(os.getcwd()) != pywikibot.config2.base_dir:
cache_paths += [
os.path.join(pywikibot.config2.base_dir, 'apicache')]
# Also process the user home cache, if it isnt the config directory
if os.path.expanduser('~/.pywikibot') != pywikibot.config2.base_dir:
cache_paths += [
os.path.join(os.path.expanduser('~/.pywikibot'), 'apicache')]
if delete:
action_func = lambda entry: entry._delete()
else:
action_func = lambda entry: pywikibot.output(entry)
if command:
try:
command_func = eval('lambda entry: ' + command)
except:
pywikibot.exception()
pywikibot.error(u'Can not compile command: %s' % command)
exit(1)
func = lambda entry: command_func(entry) and action_func(entry)
else:
func = action_func
for cache_path in cache_paths:
if len(cache_paths) > 1:
pywikibot.output(u'Processing %s' % cache_path)
process_entries(cache_path, func)
开发者ID:skamithi,项目名称:pywikibot-core,代码行数:60,代码来源:cache.py
示例7: main_script
def main_script(page, rev=None, params=NotImplemented): # pylint: disable=unused-argument
"""Main thread."""
# http://opensourcehacker.com/2011/02/23/temporarily-capturing-python-logging-output-to-a-string-buffer/
# https://docs.python.org/release/2.6/library/logging.html
from io import StringIO
import logging
# safety; default mode is safe (no writing)
pywikibot.config.simulate = True
pywikibot.output(u'--- ' * 20)
buffer = StringIO()
rootLogger = logging.getLogger()
logHandler = logging.StreamHandler(buffer)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logHandler.setFormatter(formatter)
rootLogger.addHandler(logHandler)
sys.stdout = buffer
sys.stderr = buffer
# all output to logging and stdout/stderr is catched BUT NOT lua output (!)
if rev is None:
code = page.get() # shell; "on demand"
else:
code = page.getOldVersion(rev) # crontab; scheduled
try:
exec(code)
except:
# (done according to subster in trunk and submit in rewrite/.../data/api.py)
pywikibot.exception(tb=True) # secure traceback print (from api.py submit)
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
# Remove our handler
rootLogger.removeHandler(logHandler)
logHandler.flush()
buffer.flush()
pywikibot.output(u'--- ' * 20)
# safety; restore settings
pywikibot.config.simulate = __simulate
sys.argv = __sys_argv
pywikibot.output(
u'environment: garbage; %s / memory; %s / members; %s' % (
gc.collect(),
resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * resource.getpagesize(),
len(dir())))
# 'len(dir())' is equivalent to 'len(inspect.getmembers(__main__))'
# append result to output page
if rev is None:
wiki_logger(buffer.getvalue(), page, rev)
开发者ID:metakgp,项目名称:batman,代码行数:59,代码来源:script_wui.py
示例8: run
def run(self):
"""Starts the robot."""
self.templateTitles = self.getTemplateSynonyms(self.templateTitle)
for page in self.generator:
try:
self.processPage(page)
except Exception as e:
pywikibot.exception(msg=e, tb=True)
开发者ID:anrao91,项目名称:pywikibot-core,代码行数:8,代码来源:harvest_template.py
示例9: main
def main():
local_args = pywikibot.handleArgs()
cache_paths = None
delete = False
command = None
for arg in local_args:
if command == "":
command = arg
elif arg == "-delete":
delete = True
elif arg == "-password":
command = "has_password(entry)"
elif arg == "-c":
if command:
pywikibot.error("Only one command may be executed.")
exit(1)
command = ""
else:
if not cache_paths:
cache_paths = [arg]
else:
cache_paths.append(arg)
func = None
if not cache_paths:
cache_paths = ["apicache", "tests/apicache"]
# Also process the base directory, if it isnt the current directory
if os.path.abspath(os.getcwd()) != pywikibot.config2.base_dir:
cache_paths += [os.path.join(pywikibot.config2.base_dir, "apicache")]
# Also process the user home cache, if it isnt the config directory
if os.path.expanduser("~/.pywikibot") != pywikibot.config2.base_dir:
cache_paths += [os.path.join(os.path.expanduser("~/.pywikibot"), "apicache")]
if delete:
action_func = lambda entry: entry._delete()
else:
action_func = lambda entry: pywikibot.output(entry)
if command:
try:
command_func = eval("lambda entry: " + command)
except:
pywikibot.exception()
pywikibot.error("Can not compile command: %s" % command)
exit(1)
func = lambda entry: command_func(entry) and action_func(entry)
else:
func = action_func
for cache_path in cache_paths:
if len(cache_paths) > 1:
pywikibot.output("Processing %s" % cache_path)
process_entries(cache_path, func)
开发者ID:metakgp,项目名称:batman,代码行数:58,代码来源:cache.py
示例10: test_exception
def test_exception(self):
class TestException(Exception):
pass
try:
raise TestException("Testing Exception")
except TestException:
pywikibot.exception("exception")
self.assertEqual(newstdout.getvalue(), "")
self.assertEqual(newstderr.getvalue(), "ERROR: TestException: Testing Exception\n")
开发者ID:Exal117,项目名称:pywikibot-core,代码行数:9,代码来源:ui_tests.py
示例11: treat
def treat(self, page):
pywikibot.output(u'parsing {}'.format(page))
item = pywikibot.ItemPage.fromPage(page)
if not item.exists():
pywikibot.warning(u'item not found for {}'.format(page))
return
text = page.text
code = mwparserfromhell.parse(page.text)
removed = []
for template in code.ifilter_templates():
if template.name.strip().title() != 'Autore':
continue
for pcode, pname in self.params.items():
if template.has(pname, False):
val = template.get(pname).value.strip()
if val == '' or getattr(self, 'handle_' + pcode)(val, item) is True:
template.remove(pname, keep_field=False)
removed.append(pname)
sections = {}
sbeg = None
elements = code.filter()
for el in code.ifilter_tags():
if el.tag == 'section' and el.self_closing is True:
if el.has('begin'):
sbeg = el
elif sbeg and el.has('end'):
sname = unicode(sbeg.get('begin').value)
if unicode(el.get('end').value) == sname:
start = elements.index(sbeg) + 2 + len(sbeg.attributes) * 2
sections[sname] = [sbeg] + elements[start:elements.index(el) + 1]
for scode, sname in self.params.items():
if sname in sections:
val = ''.join(map(unicode, sections[sname][1:-1])).strip()
if val == '' or getattr(self, 'handle_' + scode)(val, item) is True:
for el in sections[sname]:
code.remove(el)
removed.append(sname)
if len(removed) == 6:
remset = list(set(removed))
if len(remset) != 3:
return
removed = list(remset)
text = unicode(code)
text = re.sub('(?<=\/\>)(\n\s*)+(?=\n\<)', '', text)
comment = i18n.translate(page.site, wikidata_summary[1],
{'counter': len(removed),
'params': page.site.list_to_text(removed),
'id': item.getID()
})
try:
self.userPut(page, page.text, text, comment=comment, minor=True, botflag=True)
except Exception as e:
pywikibot.exception(e)
开发者ID:edgarskos,项目名称:wiki,代码行数:56,代码来源:itws.py
示例12: setUpClass
def setUpClass(cls):
"""
Set up the test class.
Prevent tests running if the host is down.
"""
super(CheckHostnameMixin, cls).setUpClass()
if not hasattr(cls, 'sites'):
return
for key, data in cls.sites.items():
if 'hostname' not in data:
raise Exception('%s: hostname not defined for %s'
% (cls.__name__, key))
hostname = data['hostname']
if hostname in cls._checked_hostnames:
if isinstance(cls._checked_hostnames[hostname], Exception):
raise unittest.SkipTest(
'%s: hostname %s failed (cached): %s'
% (cls.__name__, hostname,
cls._checked_hostnames[hostname]))
elif cls._checked_hostnames[hostname] is False:
raise unittest.SkipTest('%s: hostname %s failed (cached)'
% (cls.__name__, hostname))
else:
continue
e = None
try:
if '://' not in hostname:
hostname = 'http://' + hostname
r = http.fetch(uri=hostname,
default_error_handling=False)
if r.exception:
e = r.exception
else:
if r.status not in [200, 301, 302, 303, 307, 308]:
raise ServerError('HTTP status: %d' % r.status)
r.content # default decode may raise exception
except Exception as e2:
pywikibot.error('%s: accessing %s caused exception:'
% (cls.__name__, hostname))
pywikibot.exception(e2, tb=True)
e = e2
pass
if e:
cls._checked_hostnames[hostname] = e
raise unittest.SkipTest(
'%s: hostname %s failed: %s'
% (cls.__name__, hostname, e))
cls._checked_hostnames[hostname] = True
开发者ID:emijrp,项目名称:pywikibot-core,代码行数:55,代码来源:aspects.py
示例13: test_exception
def test_exception(self):
class TestException(Exception):
"""Test exception."""
try:
raise TestException('Testing Exception')
except TestException:
pywikibot.exception('exception')
self.assertEqual(newstdout.getvalue(), '')
self.assertEqual(newstderr.getvalue(), 'ERROR: TestException: Testing Exception\n')
开发者ID:metakgp,项目名称:batman,代码行数:11,代码来源:ui_tests.py
示例14: safe_execute
def safe_execute(self, method, text):
"""Execute the method and catch exceptions if enabled."""
result = None
try:
result = method(text)
except Exception as e:
if self.ignore == CANCEL_METHOD:
pywikibot.warning('Unable to perform "{0}" on "{1}"!'.format(method.__name__, self.title))
pywikibot.exception(e)
else:
raise
return text if result is None else result
开发者ID:h4ck3rm1k3,项目名称:pywikibot-core,代码行数:12,代码来源:cosmetic_changes.py
示例15: _parse_command
def _parse_command(command, name):
obj = globals().get(command)
if callable(obj):
return obj
else:
try:
return eval('lambda entry: ' + command)
except:
pywikibot.exception()
pywikibot.error(
'Cannot compile {0} command: {1}'.format(name, command))
return None
开发者ID:Kat233hryn,项目名称:pywikibot-core,代码行数:12,代码来源:cache.py
示例16: do_check
def do_check(self, page_title, rev=None, params=None):
# Create two threads as follows
# (simple 'thread' for more sophisticated code use 'threading')
try:
thread.start_new_thread(main_script, (self.refs[page_title], rev, params))
except:
# (done according to subster in trunk and submit in rewrite/.../data/api.py)
# TODO: is this error handling here needed at all??!?
pywikibot.exception(tb=True) # secure traceback print (from api.py submit)
pywikibot.warning("Unable to start thread")
wiki_logger(traceback.format_exc(), self.refs[page_title], rev)
开发者ID:hasteur,项目名称:pywikibot_scripts,代码行数:12,代码来源:script_wui.py
示例17: wrapper
def wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
except AssertionError:
tb = traceback.extract_tb(sys.exc_info()[2])
for depth, line in enumerate(tb):
if re.match('^assert[A-Z]', line[2]):
break
tb = traceback.format_list(tb[:depth])
pywikibot.error('\n' + ''.join(tb)[:-1]) # remove \n at the end
raise unittest.SkipTest('Test is allowed to fail.')
except Exception:
pywikibot.exception(tb=True)
raise unittest.SkipTest('Test is allowed to fail.')
开发者ID:Annie201,项目名称:pywikibot-core,代码行数:14,代码来源:utils.py
示例18: userIsExperienced
def userIsExperienced(self, username):
"""
Check whether is this user is experienced.
user is experienced if edits >= 50
changed to 25 // 20150309
"""
try:
user = pywikibot.User(self.site, username)
except pywikibot.InvalidTitle:
pywikibot.exception()
return False
return user.editCount() >= self.useredits
开发者ID:edgarskos,项目名称:pywikibot-bots-xqbot,代码行数:14,代码来源:vandalism.py
示例19: process_entries
def process_entries(cache_dir, func):
""" Check the contents of the cache. """
# This program tries to use file access times to determine
# whether cache files are being used.
# However file access times are not always usable.
# On many modern filesystems, they have been disabled.
# On unix, check the filesystem mount options. You may
# need to remount with 'strictatime'.
# - None = detect
# - False = dont use
# - True = always use
use_accesstime = None
if not cache_dir:
cache_dir = os.path.join(pywikibot.config2.base_dir, 'apicache')
for filename in os.listdir(cache_dir):
filepath = os.path.join(cache_dir, filename)
if use_accesstime is not False:
stinfo = os.stat(filepath)
entry = CacheEntry(cache_dir, filename)
entry._load_cache()
if use_accesstime is None:
stinfo2 = os.stat(filepath)
use_accesstime = stinfo.st_atime != stinfo2.st_atime
if use_accesstime:
# Reset access times to values before loading cache entry.
os.utime(filepath, (stinfo.st_atime, stinfo.st_mtime))
entry.stinfo = stinfo
try:
entry.parse_key()
except ParseError:
pywikibot.error(u'Problems parsing %s with key %s'
% (entry.filename, entry.key))
pywikibot.exception()
continue
try:
entry._rebuild()
except Exception:
pywikibot.error(u'Problems loading %s with key %s, %r'
% (entry.filename, entry.key, entry._parsed_key))
pywikibot.exception()
continue
func(entry)
开发者ID:anrao91,项目名称:pywikibot-core,代码行数:50,代码来源:cache.py
示例20: change
def change(self, text):
"""Execute all clean up methods and catch errors if activated."""
try:
new_text = self._change(text)
except Exception as e:
if self.ignore == CANCEL_PAGE:
pywikibot.warning(u'Skipped "{0}", because an error occured.'.format(self.title))
pywikibot.exception(e)
return False
else:
raise
else:
if self.diff:
pywikibot.showDiff(text, new_text)
return new_text
开发者ID:skamithi,项目名称:pywikibot-core,代码行数:15,代码来源:cosmetic_changes.py
注:本文中的pywikibot.exception函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论