Python faulthandler.enable() Examples
The following are 30
code examples of faulthandler.enable().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
faulthandler
, or try the search function
.
Example #1
Source File: workbench.py From thonny with MIT License | 6 votes |
def _init_diagnostic_logging(self) -> None: logFormatter = logging.Formatter("%(levelname)s: %(message)s") root_logger = logging.getLogger() log_file = os.path.join(THONNY_USER_DIR, "frontend.log") file_handler = logging.FileHandler(log_file, encoding="UTF-8", mode="w") file_handler.setFormatter(logFormatter) file_handler.setLevel(self._get_logging_level()) root_logger.addHandler(file_handler) console_handler = logging.StreamHandler(sys.stdout) console_handler.setFormatter(logFormatter) console_handler.setLevel(self._get_logging_level()) root_logger.addHandler(console_handler) root_logger.setLevel(self._get_logging_level()) import faulthandler fault_out = open(os.path.join(THONNY_USER_DIR, "frontend_faults.log"), mode="w") faulthandler.enable(fault_out)
Example #2
Source File: __init__.py From declaracad with GNU General Public License v3.0 | 6 votes |
def main(): faulthandler.enable() parser = ArgumentParser() subparsers = parser.add_subparsers(help='DeclaraCAD subcommands') viewer = subparsers.add_parser("view", help="View the given file") viewer.set_defaults(func=launch_viewer) viewer.add_argument("file", help="File to view") viewer.add_argument("-w", "--watch", action='store_true', help="Watch for file changes and autoreload") viewer.add_argument("-f", "--frameless", action='store_true', help="Frameless viewer") exporter = subparsers.add_parser("export", help="Export the given file") exporter.set_defaults(func=launch_exporter) exporter.add_argument("options", help="File to export or json string of " "ExportOption parameters") args = parser.parse_args() # Start the app launcher = getattr(args, 'func', launch_workbench) launcher(args)
Example #3
Source File: test_faulthandler.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
def test_is_enabled(self): orig_stderr = sys.stderr try: # regrtest may replace sys.stderr by io.StringIO object, but # faulthandler.enable() requires that sys.stderr has a fileno() # method sys.stderr = sys.__stderr__ was_enabled = faulthandler.is_enabled() try: faulthandler.enable() self.assertTrue(faulthandler.is_enabled()) faulthandler.disable() self.assertFalse(faulthandler.is_enabled()) finally: if was_enabled: faulthandler.enable() else: faulthandler.disable() finally: sys.stderr = orig_stderr
Example #4
Source File: app.py From abseil-py with Apache License 2.0 | 6 votes |
def _run_init( argv, flags_parser, ): """Does one-time initialization and re-parses flags on rerun.""" if _run_init.done: return flags_parser(argv) command_name.make_process_name_useful() # Set up absl logging handler. logging.use_absl_handler() args = _register_and_parse_flags_with_usage( argv=argv, flags_parser=flags_parser, ) if faulthandler: try: faulthandler.enable() except Exception: # pylint: disable=broad-except # Some tests verify stderr output very closely, so don't print anything. # Disabled faulthandler is a low-impact error. pass _run_init.done = True return args
Example #5
Source File: test_faulthandler.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 6 votes |
def test_is_enabled(self): orig_stderr = sys.stderr try: # regrtest may replace sys.stderr by io.StringIO object, but # faulthandler.enable() requires that sys.stderr has a fileno() # method sys.stderr = sys.__stderr__ was_enabled = faulthandler.is_enabled() try: faulthandler.enable() self.assertTrue(faulthandler.is_enabled()) faulthandler.disable() self.assertFalse(faulthandler.is_enabled()) finally: if was_enabled: faulthandler.enable() else: faulthandler.disable() finally: sys.stderr = orig_stderr
Example #6
Source File: views.py From PyDev.Debugger with Eclipse Public License 1.0 | 6 votes |
def get_name(request): import faulthandler faulthandler.enable() # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: form = NameForm(data={'your_name': 'unknown name'}) return render(request, 'my_app/name.html', {'form': form})
Example #7
Source File: process.py From mitogen with BSD 3-Clause "New" or "Revised" License | 6 votes |
def common_setup(enable_affinity=True, _init_logging=True): save_pid('controller') ansible_mitogen.logging.set_process_name('top') if _init_logging: ansible_mitogen.logging.setup() if enable_affinity: ansible_mitogen.affinity.policy.assign_controller() mitogen.utils.setup_gil() if faulthandler is not None: faulthandler.enable() MuxProcess.profiling = getenv_int('MITOGEN_PROFILING') > 0 if MuxProcess.profiling: mitogen.core.enable_profiling() MuxProcess.cls_original_env = dict(os.environ) increase_open_file_limit()
Example #8
Source File: debug.py From tf-pose with Apache License 2.0 | 6 votes |
def enableFaulthandler(): """ Enable faulthandler for all threads. If the faulthandler package is available, this function disables and then re-enables fault handling for all threads (this is necessary to ensure any new threads are handled correctly), and returns True. If faulthandler is not available, then returns False. """ try: import faulthandler # necessary to disable first or else new threads may not be handled. faulthandler.disable() faulthandler.enable(all_threads=True) return True except ImportError: return False
Example #9
Source File: main.py From enamlx with MIT License | 6 votes |
def main(): logging.basicConfig(level='DEBUG',stream=sys.stdout,format='%(asctime)s %(levelname)-8s %(name)-15s %(message)s') try: import faulthandler faulthandler.enable() except ImportError: pass with enaml.imports(): from view import Main app = QtApplication() profiler = cProfile.Profile() view = Main() view.show() # Start the application event loop profiler.enable() app.start() profiler.disable() profiler.print_stats('tottime')
Example #10
Source File: crashsignal.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def destroy_crashlogfile(self): """Clean up the crash log file and delete it.""" if self._crash_log_file is None: return # We use sys.__stderr__ instead of sys.stderr here so this will still # work when sys.stderr got replaced, e.g. by "Python Tools for Visual # Studio". if sys.__stderr__ is not None: faulthandler.enable(sys.__stderr__) else: faulthandler.disable() # type: ignore[unreachable] try: self._crash_log_file.close() os.remove(self._crash_log_file.name) except OSError: log.destroy.exception("Could not remove crash log!")
Example #11
Source File: earlyinit.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def configure_pyqt(): """Remove the PyQt input hook and enable overflow checking. Doing this means we can't use the interactive shell anymore (which we don't anyways), but we can use pdb instead. """ from PyQt5 import QtCore QtCore.pyqtRemoveInputHook() try: QtCore.pyqt5_enable_new_onexit_scheme( # type: ignore[attr-defined] True) except AttributeError: # Added in PyQt 5.13 somewhere, going to be the default in 5.14 pass from qutebrowser.qt import sip try: # Added in sip 4.19.4 sip.enableoverflowchecking(True) # type: ignore[attr-defined] except AttributeError: pass
Example #12
Source File: earlyinit.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def _check_modules(modules): """Make sure the given modules are available.""" from qutebrowser.utils import log for name, text in modules.items(): try: # https://bitbucket.org/fdik/pypeg/commits/dd15ca462b532019c0a3be1d39b8ee2f3fa32f4e # pylint: disable=bad-continuation with log.ignore_py_warnings( category=DeprecationWarning, message=r'invalid escape sequence' ), log.ignore_py_warnings( category=ImportWarning, message=r'Not importing directory .*: missing __init__' ), log.ignore_py_warnings( category=DeprecationWarning, message=r'the imp module is deprecated', ): # pylint: enable=bad-continuation importlib.import_module(name) except ImportError as e: _die(text, e)
Example #13
Source File: testing.py From pscript with BSD 2-Clause "Simplified" License | 5 votes |
def _enable_faulthandler(): """ Enable faulthandler (if we can), so that we get tracebacks on segfaults. """ try: import faulthandler faulthandler.enable() print('Faulthandler enabled') except Exception: print('Could not enable faulthandler')
Example #14
Source File: test_faulthandler.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_stderr_None(self): # Issue #21497: provide a helpful error if sys.stderr is None, # instead of just an attribute error: "None has no attribute fileno". with self.check_stderr_none(): faulthandler.enable() with self.check_stderr_none(): faulthandler.dump_traceback() if hasattr(faulthandler, 'dump_traceback_later'): with self.check_stderr_none(): faulthandler.dump_traceback_later(1e-3) if hasattr(faulthandler, "register"): with self.check_stderr_none(): faulthandler.register(signal.SIGUSR1)
Example #15
Source File: verify.py From s3ql with GNU General Public License v3.0 | 5 votes |
def main(args=None): faulthandler.enable() faulthandler.register(signal.SIGUSR1) if args is None: args = sys.argv[1:] options = parse_args(args) setup_logging(options) backend_factory = get_backend_factory(options) # Retrieve metadata with backend_factory() as backend: (param, db) = get_metadata(backend, options.cachepath) retrieve_objects(db, backend_factory, options.corrupted_file, options.missing_file, thread_count=options.parallel, full=options.data, offset=options.start_with) if options.corrupted_file.tell() or options.missing_file.tell(): sys.exit(46) else: os.unlink(options.corrupted_file.name) os.unlink(options.missing_file.name) sys.exit(0)
Example #16
Source File: test_faulthandler.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_read_null(self): self.check_fatal_error(""" import faulthandler faulthandler.enable() faulthandler._read_null() """, 3, # Issue #12700: Read NULL raises SIGILL on Mac OS X Lion '(?:Segmentation fault|Bus error|Illegal instruction)')
Example #17
Source File: absltest.py From abseil-py with Apache License 2.0 | 5 votes |
def _register_sigterm_with_faulthandler(): # type: () -> None """Have faulthandler dump stacks on SIGTERM. Useful to diagnose timeouts.""" if faulthandler and getattr(faulthandler, 'register', None): # faulthandler.register is not avaiable on Windows. # faulthandler.enable() is already called by app.run. try: faulthandler.register(signal.SIGTERM, chain=True) # pytype: disable=module-attr except Exception as e: # pylint: disable=broad-except sys.stderr.write('faulthandler.register(SIGTERM) failed ' '%r; ignoring.\n' % e)
Example #18
Source File: test.py From pscript with BSD 2-Clause "Simplified" License | 5 votes |
def _enable_faulthandler(): """ Enable faulthandler (if we can), so that we get tracebacks on segfaults. """ try: import faulthandler faulthandler.enable() print('Faulthandler enabled') except Exception: print('Could not enable faulthandler')
Example #19
Source File: absltest.py From abseil-py with Apache License 2.0 | 5 votes |
def _create(cls, base_path, file_path, content, mode, encoding, errors): # type: (Text, Optional[Text], AnyStr, Text, Text, Text) -> Tuple[_TempFile, Text] # pylint: enable=line-too-long """Module-private: create a tempfile instance.""" if file_path: cleanup_path = os.path.join(base_path, _get_first_part(file_path)) path = os.path.join(base_path, file_path) _makedirs_exist_ok(os.path.dirname(path)) # The file may already exist, in which case, ensure it's writable so that # it can be truncated. if os.path.exists(path) and not os.access(path, os.W_OK): stat_info = os.stat(path) os.chmod(path, stat_info.st_mode | stat.S_IWUSR) else: _makedirs_exist_ok(base_path) fd, path = tempfile.mkstemp(dir=str(base_path)) os.close(fd) cleanup_path = path tf = cls(path) if content: if isinstance(content, six.text_type): tf.write_text(content, mode=mode, encoding=encoding, errors=errors) else: tf.write_bytes(content, mode) else: tf.write_bytes(b'') return tf, cleanup_path
Example #20
Source File: test_faulthandler.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_gil_released(self): self.check_fatal_error(""" import faulthandler faulthandler.enable() faulthandler._sigsegv(True) """, 3, 'Segmentation fault')
Example #21
Source File: local_elastic_agent.py From elastic with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _wrap(local_rank, ret_vals, dist_infos, fn, args): import faulthandler try: faulthandler.enable(all_threads=True) except Exception as e: log.warn( "Unable to enable fault handler. Failure signals on worker process will not dump tracebacks", exc_info=e, ) info = dist_infos[local_rank] os.environ["LOCAL_RANK"] = str(local_rank) os.environ["RANK"] = str(info.rank) os.environ["GROUP_RANK"] = str(info.group_rank) os.environ["ROLE_RANK"] = str(info.role_rank) os.environ["LOCAL_WORLD_SIZE"] = str(info.local_world_size) os.environ["WORLD_SIZE"] = str(info.world_size) os.environ["ROLE_WORLD_SIZE"] = str(info.role_world_size) os.environ["MASTER_ADDR"] = info.master_addr os.environ["MASTER_PORT"] = str(info.master_port) os.environ["TORCHELASTIC_RESTART_COUNT"] = str(info.restart_count) os.environ["TORCHELASTIC_MAX_RESTARTS"] = str(info.max_restarts) os.environ["TORCHELASTIC_RUN_ID"] = info.run_id ret = fn(*args) ret_vals[info.rank] = ret
Example #22
Source File: testing.py From flexx with BSD 2-Clause "Simplified" License | 5 votes |
def _enable_faulthandler(): """ Enable faulthandler (if we can), so that we get tracebacks on segfaults. """ try: import faulthandler faulthandler.enable() print('Faulthandler enabled') except Exception: print('Could not enable faulthandler')
Example #23
Source File: test.py From flexx with BSD 2-Clause "Simplified" License | 5 votes |
def _enable_faulthandler(): """ Enable faulthandler (if we can), so that we get tracebacks on segfaults. """ try: import faulthandler faulthandler.enable() print('Faulthandler enabled') except Exception: print('Could not enable faulthandler')
Example #24
Source File: parallel.py From lkpy with MIT License | 5 votes |
def _initialize_worker(log_queue, seed): "Initialize a worker process." global __is_worker __is_worker = True faulthandler.enable() if seed is not None: init_rng(seed) if log_queue is not None: h = logging.handlers.QueueHandler(log_queue) root = logging.getLogger() root.addHandler(h) root.setLevel(logging.DEBUG) h.setLevel(logging.DEBUG)
Example #25
Source File: run.py From costar_plan with Apache License 2.0 | 5 votes |
def main(): args = getArgs() # get a traceback on segfault faulthandler.enable() if args.launch: launch_main(argv=['roslaunch', 'ctp_integration', 'bringup.launch'], real_args=args, fn_to_call=collect_data) else: # assume ros was already running and start collecting data return collect_data(args)
Example #26
Source File: test_faulthandler.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_stderr_None(self): # Issue #21497: provide an helpful error if sys.stderr is None, # instead of just an attribute error: "None has no attribute fileno". with self.check_stderr_none(): faulthandler.enable() with self.check_stderr_none(): faulthandler.dump_traceback() if hasattr(faulthandler, 'dump_traceback_later'): with self.check_stderr_none(): faulthandler.dump_traceback_later(1e-3) if hasattr(faulthandler, "register"): with self.check_stderr_none(): faulthandler.register(signal.SIGUSR1)
Example #27
Source File: test_faulthandler.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_disable(self): code = """ import faulthandler faulthandler.enable() faulthandler.disable() faulthandler._sigsegv() """ not_expected = 'Fatal Python error' stderr, exitcode = self.get_output(code) stderr = '\n'.join(stderr) self.assertTrue(not_expected not in stderr, "%r is present in %r" % (not_expected, stderr)) self.assertNotEqual(exitcode, 0)
Example #28
Source File: test_faulthandler.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_enable_single_thread(self): self.check_fatal_error(""" import faulthandler faulthandler.enable(all_threads=False) faulthandler._sigsegv() """, 3, 'Segmentation fault', all_threads=False)
Example #29
Source File: test_faulthandler.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_enable_file(self): with temporary_filename() as filename: self.check_fatal_error(""" import faulthandler output = open({filename}, 'wb') faulthandler.enable(output) faulthandler._sigsegv() """.format(filename=repr(filename)), 4, 'Segmentation fault', filename=filename)
Example #30
Source File: __init__.py From CogAlg with MIT License | 5 votes |
def _init_tests(): # CPython's faulthandler since v3.6 handles exceptions on Windows # https://bugs.python.org/issue23848 but until v3.6.4 it was printing # non-fatal exceptions https://bugs.python.org/issue30557 import platform if not (sys.platform == 'win32' and (3, 6) < sys.version_info < (3, 6, 4) and platform.python_implementation() == 'CPython'): import faulthandler faulthandler.enable() # The version of FreeType to install locally for running the # tests. This must match the value in `setupext.py` LOCAL_FREETYPE_VERSION = '2.6.1' from matplotlib import ft2font if (ft2font.__freetype_version__ != LOCAL_FREETYPE_VERSION or ft2font.__freetype_build_type__ != 'local'): _log.warning( "Matplotlib is not built with the correct FreeType version to run " "tests. Set local_freetype=True in setup.cfg and rebuild. " "Expect many image comparison failures below. " "Expected freetype version {0}. " "Found freetype version {1}. " "Freetype build type is {2}local".format( LOCAL_FREETYPE_VERSION, ft2font.__freetype_version__, "" if ft2font.__freetype_build_type__ == 'local' else "not ")) try: import pytest except ImportError: print("matplotlib.test requires pytest to run.") raise