def _tcp_proc(self, addrinfo, task=None):
"""
Internal use only.
"""
task.set_daemon()
sock = addrinfo.tcp_sock
while 1:
try:
conn, addr = yield sock.accept()
except ssl.SSLError as err:
logger.debug('SSL connection failed: %s', str(err))
continue
except GeneratorExit:
break
except:
logger.debug(traceback.format_exc())
continue
SysTask(self._tcp_conn_proc, conn, addrinfo)
python类format_exc()的实例源码
def line_reader(apipe, coro=None):
nlines = 0
while True:
try:
line = yield apipe.readline()
except:
asyncoro.logger.debug('read failed')
asyncoro.logger.debug(traceback.format_exc())
break
nlines += 1
if not line:
break
print(line.decode())
raise StopIteration(nlines)
# asyncoro.logger.setLevel(asyncoro.Logger.DEBUG)
def peer_status(task):
_Peer._lock.acquire()
if isinstance(task, Task):
# if there is another status_task, add or replace?
for peer in _Peer.peers.itervalues():
try:
task.send(PeerStatus(peer.location, peer.name, PeerStatus.Online))
except:
logger.debug(traceback.format_exc())
break
else:
_Peer.status_task = task
elif task is None:
_Peer.status_task = None
else:
logger.warning('invalid peer status task ignored')
_Peer._lock.release()
def line_reader(apipe, coro=None):
nlines = 0
while True:
try:
line = yield apipe.readline()
except:
asyncoro.logger.debug('read failed')
asyncoro.logger.debug(traceback.format_exc())
break
nlines += 1
if not line:
break
print(line.decode())
raise StopIteration(nlines)
# asyncoro.logger.setLevel(asyncoro.Logger.DEBUG)
def terminate(self):
if hasattr(self.cmd_write, 'getsockname'):
self.cmd_write.close()
self.cmd_read.close()
for fd in self._fds.itervalues():
try:
self._poller.unregister(fd._fileno)
except:
logger.warning('unregister of %s failed with %s',
fd._fileno, traceback.format_exc())
fd._notifier = None
self._fds.clear()
self._timeouts = []
if hasattr(self._poller, 'terminate'):
self._poller.terminate()
self._poller = None
self.cmd_read = self.cmd_write = None
def _tcp_proc(self, addrinfo, task=None):
"""
Internal use only.
"""
task.set_daemon()
sock = addrinfo.tcp_sock
while 1:
try:
conn, addr = yield sock.accept()
except ssl.SSLError as err:
logger.debug('SSL connection failed: %s', str(err))
continue
except GeneratorExit:
break
except:
logger.debug(traceback.format_exc())
continue
SysTask(self._tcp_conn_proc, conn, addrinfo)
def line_reader(apipe, coro=None):
nlines = 0
while True:
try:
line = yield apipe.readline()
except:
asyncoro.logger.debug('read failed')
asyncoro.logger.debug(traceback.format_exc())
break
nlines += 1
if not line:
break
print(line.decode())
raise StopIteration(nlines)
# asyncoro.logger.setLevel(asyncoro.Logger.DEBUG)
def terminate(self):
if hasattr(self.cmd_write, 'getsockname'):
self.cmd_write.close()
self.cmd_read.close()
for fd in self._fds.values():
try:
self._poller.unregister(fd._fileno)
except:
logger.warning('unregister of %s failed with %s',
fd._fileno, traceback.format_exc())
fd._notifier = None
self._fds.clear()
self._timeouts = []
if hasattr(self._poller, 'terminate'):
self._poller.terminate()
self._poller = None
self.cmd_read = self.cmd_write = None
def build(self, file):
if self.built:
raise PermissionError("You cannot build multiple times!")
if not self.loaded:
self.load(file)
old = os.getcwd()
sys.path.append(os.path.dirname(os.path.abspath(file))) # for module import that aren't "include" call
try:
content = open(file, "rb").read()
os.chdir(os.path.dirname(os.path.abspath(file))) # set the current working directory, for open() etc.
exec(compile(content, file, 'exec'), self.user_functions)
except Exception as err:
print("An exception occured while building: ", file=sys.stderr)
lines = traceback.format_exc(None, err).splitlines()
print(" " + lines[-1], file=sys.stderr)
for l in lines[3:-1]:
print(l, file=sys.stderr)
exit(1)
os.chdir(old)
sys.path.remove(os.path.dirname(os.path.abspath(file)))
self.built = True
def load(self, file):
if self.loaded:
return
sys.path.append(os.path.dirname(os.path.abspath(file))) # for module import that aren't "include" call
old = os.getcwd()
try:
content = open(file, "rb").read()
os.chdir(os.path.dirname(os.path.abspath(file))) # set the current working directory, for open() etc.
exec(compile(content, file, 'exec'), self.user_functions)
except Exception as err:
print("An exception occured while loading: ", file=sys.stderr)
lines = traceback.format_exc(None, err).splitlines()
print(" " + lines[-1], file=sys.stderr)
for l in lines[3:-1]:
print(l, file=sys.stderr)
exit(1)
os.chdir(old)
sys.path.remove(os.path.dirname(os.path.abspath(file)))
self.loaded = True
self.mem_offset = 0
def include(self, incfile: str):
old = self.current_path
self.current_path = os.path.join(old, os.path.dirname(incfile))
path = os.path.join(self.current_path, os.path.basename(incfile))
sys.path.append(self.current_path)
try:
content = open(path, "rb").read()
os.chdir(self.current_path) # set the current working directory, for open() etc.
exec(compile(content, path, 'exec'), self.user_functions)
except Exception as err:
print("An exception occured while building: ", file=sys.stderr)
lines = traceback.format_exc(None, err).splitlines()
print(" " + lines[-1], file=sys.stderr)
for l in lines[3:-1]:
print(l, file=sys.stderr)
exit(1)
sys.path.remove(self.current_path)
os.chdir(old)
self.current_path = old
def generate2():
"""
Call an external Python 2 program to retrieve the AST symbols of that
language version
:return:
"""
import subprocess as sp
import tempfile, shutil, sys, traceback
tempdir = tempfile.mkdtemp()
tempfile = os.path.join(tempdir, "py2_ast_code.py")
py2_proc_out = ""
try:
with open(tempfile, 'w') as py2code:
py2code.write(generate_str + WRITESYMS_CODE)
py2_proc_out = sp.check_output(["python2", tempfile]).decode()
finally:
try:
shutil.rmtree(tempdir)
except:
print("Warning: error trying to delete the temporal directory:", file=sys.stderr)
print(traceback.format_exc(), file=sys.stderr)
return set(py2_proc_out.splitlines())
def setup_py(self):
assert self.source_dir, "No source dir for %s" % self
try:
import setuptools # noqa
except ImportError:
if get_installed_version('setuptools') is None:
add_msg = "Please install setuptools."
else:
add_msg = traceback.format_exc()
# Setuptools is not available
raise InstallationError(
"Could not import setuptools which is required to "
"install from a source distribution.\n%s" % add_msg
)
setup_py = os.path.join(self.setup_py_dir, 'setup.py')
# Python2 __file__ should not be unicode
if six.PY2 and isinstance(setup_py, six.text_type):
setup_py = setup_py.encode(sys.getfilesystemencoding())
return setup_py
def internal_server_error(error):
logger.error(error)
logger.error(traceback.format_exc())
if "username" in session:
if "500" in session and "500_title" in session:
reason = session['500']
title = session['500_title']
session.pop('500', None)
session.pop('500_title', None)
else:
reason = '''The server encountered something unexpected that didn't allow it to complete the request. We apologize.You can go back to
<a href="/dashboard/">dashboard</a> or <a href="/logout">log out</a>'''
title = 'Internal Server Error'
return render_template('error/500.html', mysession = session, reason = reason, title = title)
else:
return redirect('/login/')
def setup_py(self):
assert self.source_dir, "No source dir for %s" % self
try:
import setuptools # noqa
except ImportError:
if get_installed_version('setuptools') is None:
add_msg = "Please install setuptools."
else:
add_msg = traceback.format_exc()
# Setuptools is not available
raise InstallationError(
"Could not import setuptools which is required to "
"install from a source distribution.\n%s" % add_msg
)
setup_py = os.path.join(self.setup_py_dir, 'setup.py')
# Python2 __file__ should not be unicode
if six.PY2 and isinstance(setup_py, six.text_type):
setup_py = setup_py.encode(sys.getfilesystemencoding())
return setup_py
def main():
argument_spec = dict(
compress=dict(default=True, type='bool'),
dest=dict(type='str'),
mode=dict(default='0644', type='str'),
sha1=dict(default=None, type='str'),
src=dict(required=True, type='str')
)
module = AnsibleModule(argument_spec)
dest = module.params.get('dest')
try:
if dest:
copy_to_host(module)
else:
copy_from_host(module)
except Exception:
module.exit_json(failed=True, changed=True,
msg=repr(traceback.format_exc()))
# import module snippets
def main():
module = AnsibleModule(
argument_spec=openstack_full_argument_spec(
password=dict(required=True, no_log=True, type='str'),
project=dict(required=True, type='str'),
role=dict(required=True, type='str'),
user=dict(required=True, type='str'),
service=dict(required=True, type='str'),
)
)
try:
changed = True
cloud = shade.operator_cloud(**module.params)
getattr(SanityChecks, module.params.pop("service"))(cloud)
module.exit_json(changed=changed)
except Exception:
module.exit_json(failed=True, changed=True,
msg=repr(traceback.format_exc()))
# import module snippets
def __init__(self, resource=None ):
self._mgr_lock = threading.Lock()
self._ecm = None
self._logger = logging.getLogger("ossie.events.Manager")
self._logger.setLevel(logging.INFO)
self._allow = True
self._registrations=[]
if resource :
try:
self._logger.debug("Requesting Domain Manager Access....")
dom = resource.getDomainManager()
self._logger.debug("Requesting EventChannelManager Access....")
self._ecm = dom.getRef()._get_eventChannelMgr()
self._logger.debug("Acquired reference to EventChannelManager")
except:
#print traceback.format_exc()
self._logger.warn("EventChannelManager - unable to resolve DomainManager's EventChannelManager ")
pass
def Subscriber(self, channel_name, registrationId=""):
self._mgr_lock.acquire()
self._logger.debug("Requesting Subscriber for Channel:" + str(channel_name) )
sub = None
try:
if self._ecm:
ereg = EventChannelManager.EventRegistration( channel_name = channel_name, reg_id = registrationId)
self._logger.debug("Requesting Channel:" + str(channel_name) + " from Domain's EventChannelManager ")
registration = self._ecm.registerResource( ereg )
sub = EM_Subscriber( self, registration )
self._logger.debug("Channel:" + str(channel_name) + " Reg-Id:" + str(registration.reg.reg_id))
self._registrations.append( registration )
except:
#print traceback.format_exc()
self._logger.error("Unable to create Subscriber for Channel:" + str(channel_name ))
finally:
self._mgr_lock.release()
return sub
def maker(name):
my_level = getattr(logging, name.upper()) if name != 'exception' else logging.ERROR
altname = (name if name != 'exception' else 'error').upper()
def _log(self, msg, *args, **kwargs):
exc = kwargs.pop('exc_info', None) or name == 'exception'
tb = ('\n' + traceback.format_exc().strip()) if exc else ''
if args:
try:
msg = msg % args
except:
self.exception(
"Exception raised while formatting message:\n%s\n%r",
msg, args)
msg += tb
# todo: check level before printing
if self.level <= my_level:
print("%s %s %s"%(time.asctime(), altname, msg))
_log.__name__ = name
return _log
def _serve():
from .util import is_exiting, sub_warning
while 1:
try:
conn = _listener.accept()
handle_wanted, destination_pid = conn.recv()
_cache.remove(handle_wanted)
send_handle(conn, handle_wanted, destination_pid)
close(handle_wanted)
conn.close()
except:
if not is_exiting():
import traceback
sub_warning(
'thread for sharing handles raised exception :\n' +
'-'*79 + '\n' + traceback.format_exc() + '-'*79
)
#
# Functions to be used for pickling/unpickling objects with handles
#
def run(self):
log.debug("starting event registry thread")
while True:
callback, cb, event_type, event_data = self._callback_queue.get()
kwargs = callback["kwargs"]
kwargs["cb"] = cb
kwargs["event_type"] = event_type
kwargs["event_data"] = event_data
try:
callback["func"](*callback["args"], **kwargs)
except Exception as e:
with self._error_lock:
self._errors.append({"exception": traceback.format_exc(), "timestamp": time.time(),
"callback_func": callback["func"].__name__,
"event_type": event_type, "event_data": event_data})
def LOGEXCEPTION(message):
if LOGGER:
LOGGER.exception(message)
else:
print(
'%sZ [EXC!]: %s\nexception was: %s' % (
datetime.utcnow().isoformat(),
message, format_exc()
)
)
#######################
## UTILITY FUNCTIONS ##
#######################
# Utility function to report best scores
# modified from a snippet taken from:
# http://scikit-learn.org/stable/auto_examples/model_selection/plot_randomized_search.html
def LOGEXCEPTION(message):
if LOGGER:
LOGGER.exception(message)
else:
print(
'%sZ [EXC!]: %s\nexception was: %s' % (
datetime.utcnow().isoformat(),
message, format_exc()
)
)
########################
## COLUMN DEFINITIONS ##
########################
# LC column definitions
# the first elem is the column description, the second is the format to use when
# writing a CSV LC column, the third is the type to use when parsing a CSV LC
# column
def LOGEXCEPTION(message):
if LOGGER:
LOGGER.exception(message)
else:
print(
'%sZ [EXC!]: %s\nexception was: %s' % (
datetime.utcnow().isoformat(),
message, format_exc()
)
)
###################
## USEFUL CONFIG ##
###################
# used to find HATIDs
def LOGEXCEPTION(message):
if LOGGER:
LOGGER.exception(message)
else:
print(
'%sZ [EXC!]: %s\nexception was: %s' % (
dtime.utcnow().isoformat(),
message, format_exc()
)
)
###############################################
## MAGIC CONSTANTS FOR 2MASS TO COUSINS/SDSS ##
###############################################
# converting from JHK to BVRI
def LOGEXCEPTION(message):
if LOGGER:
LOGGER.exception(message)
else:
print(
'%sZ [EXC!]: %s\nexception was: %s' % (
datetime.utcnow().isoformat(),
message, format_exc()
)
)
###################
## LOCAL IMPORTS ##
###################
# LC reading functions
def LOGEXCEPTION(message):
if LOGGER:
LOGGER.exception(message)
else:
print(
'%sZ [EXC!]: %s\nexception was: %s' % (
datetime.utcnow().isoformat(),
message, format_exc()
)
)
###################
## LOCAL IMPORTS ##
###################
def LOGEXCEPTION(message):
if LOGGER:
LOGGER.exception(message)
else:
print(
'%sZ [EXC!]: %s\nexception was: %s' % (
datetime.utcnow().isoformat(),
message, format_exc()
)
)
###########################
## FLARE MODEL FUNCTIONS ##
###########################
def LOGEXCEPTION(message):
if LOGGER:
LOGGER.exception(message)
else:
print(
'%sZ [EXC!]: %s\nexception was: %s' % (
datetime.utcnow().isoformat(),
message, format_exc()
)
)
########################
## SOME OTHER IMPORTS ##
########################