Python os.abort() Examples

The following are 30 code examples of os.abort(). 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 os , or try the search function .
Example #1
Source File: macro.py    From magics-python with Apache License 2.0 6 votes vote down vote up
def execute(self, key):
        file = "data%d" % numpy.random.randint(1, 1000)
        odb = "%s.odb" % file
        context.tmp.append(odb)
        cmd = (
            'odbsql -q "'
            + self.args["query"]
            + '" -i '
            + self.args["path"]
            + " -f newodb -o "
            + odb
        )
        print(cmd)
        if os.system(cmd):
            print("Error in filtering ODB data... Aborting")
            os.abort()
        Magics.setc("odb_filename", odb) 
Example #2
Source File: vsctl.py    From ryu with Apache License 2.0 6 votes vote down vote up
def _do_main(self, commands):
        """
        :type commands: list of VSCtlCommand
        """
        self._reset()
        self._init_schema_helper()
        self._run_prerequisites(commands)

        idl_ = idl.Idl(self.remote, self.schema_helper)
        seqno = idl_.change_seqno
        while True:
            self._idl_wait(idl_, seqno)

            seqno = idl_.change_seqno
            if self._do_vsctl(idl_, commands):
                break

            if self.txn:
                self.txn.abort()
                self.txn = None
            # TODO:XXX
            # ovsdb_symbol_table_destroy(symtab)

        idl_.close() 
Example #3
Source File: pixiv-beta.py    From Pixiv-Crawler with GNU General Public License v3.0 6 votes vote down vote up
def update_collection_set(cls, item, response ,spider):
        # if cls.entry == "COLLECTION":
        cls.collection_set.add(item["pid"].split('_')[0])
        cls.process = len(cls.collection_set) - cls.init_colletion_set_size
        # for debug only
        if cls.process > cls.maxsize:
            if cls.entry == "COLLECTION":
                with open("./.trace", "wb") as f:
                    pickle.dump(cls.collection_set, f)

            # store .json file
            f = open("data_{0}.json".format('_'.join(cf.get('SRH', 'TAGS').split(" "))), 'w')
            data = [item.__dict__() for item in cls.data]
            json.dump(data, f)

            print("Crawling complete, got {0} data".format(len(cls.data)))
            f.close()
            os.abort()
            # raise CloseSpider
            # cls.signalManger.send_catch_log(signal=signals.spider_closed) 
Example #4
Source File: pipeline.py    From Comparative-Annotation-Toolkit with Apache License 2.0 6 votes vote down vote up
def __start(self):
        "do work of starting the process"
        self.statusPipe = _StatusPipe()
        self.started = True  # do first to prevent restarts on error
        self.pid = os.fork()
        if self.pid == 0:
            try:
                self.__childStart()
            finally:
                os.abort() # should never make it here
        else:
            self.__parentStart() 
Example #5
Source File: test_subprocess.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_run_abort(self):
        # returncode handles signal termination
        with _SuppressCoreFiles():
            p = subprocess.Popen([sys.executable, "-c",
                                  "import os; os.abort()"])
            p.wait()
        self.assertEqual(-p.returncode, signal.SIGABRT) 
Example #6
Source File: test_subprocess.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_run_abort(self):
        # returncode handles signal termination
        with _SuppressCoreFiles():
            p = subprocess.Popen([sys.executable, "-c",
                                  "import os; os.abort()"])
            p.wait()
        self.assertEqual(-p.returncode, signal.SIGABRT) 
Example #7
Source File: profiling.py    From pykit with MIT License 6 votes vote down vote up
def start_mem_check_thread(threshold=1024 * 1024 * 1024,
                           gc=False,
                           size_range=None,
                           interval=1
                           ):
    """
    Start a thread in background and in daemon mode, to watch memory usage.
    If memory this process is using beyond `threshold`, a memory usage profile
    is made and is written to root logger. And process is aborted.

    `threshold`:    maximum memory a process can use before abort.
    `gc`:           whether to run gc every time before checking memory usage.
    `size_range`:   in tuple, dump only object of size in this range.
    `interval`:     memory check interval.
    """

    options = {
        'threshold': threshold,
        'gc': gc,
        'size_range': size_range,
        'interval': interval,
    }

    th = threading.Thread(target=mem_check, args=(options,))
    th.daemon = True
    th.start()

    return th 
Example #8
Source File: profiling.py    From pykit with MIT License 6 votes vote down vote up
def mem_check(opts):

    while True:

        if opts['gc']:
            try:
                gc.collect()
            except Exception as e:
                logging.exception(repr(e) + ' while gc.collect()')

        try:
            rss = psutil.Process(os.getpid()).memory_info().rss

            logging.info('current memory used: {rss}'.format(rss=rss))

            if rss > opts['threshold']:
                memory_dump(opts)
                os.abort()
        except Exception as e:
            logging.exception(repr(e) + ' while checking memory usage')

        finally:
            time.sleep(opts['interval']) 
Example #9
Source File: test_subprocess.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_run_abort(self):
        # returncode handles signal termination
        with support.SuppressCrashReport():
            p = subprocess.Popen([sys.executable, "-c",
                                  'import os; os.abort()'])
            p.wait()
        self.assertEqual(-p.returncode, signal.SIGABRT) 
Example #10
Source File: test_subprocess.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_run_abort(self):
        # returncode handles signal termination
        with support.SuppressCrashReport():
            p = subprocess.Popen([sys.executable, "-c",
                                  'import os; os.abort()'])
            p.wait()
        self.assertEqual(-p.returncode, signal.SIGABRT) 
Example #11
Source File: indexer.py    From virtualchain with GNU General Public License v3.0 6 votes vote down vote up
def db_query_execute(cls, cur, query, values, verbose=True):
        """
        Execute a query.
        Handle db timeouts.
        Abort on failure.
        """
        timeout = 1.0

        if verbose:
            log.debug(cls.db_format_query(query, values))

        while True:
            try:
                ret = cur.execute(query, values)
                return ret
            except sqlite3.OperationalError as oe:
                if oe.message == "database is locked":
                    timeout = timeout * 2 + timeout * random.random()
                    log.error("Query timed out due to lock; retrying in %s: %s" % (timeout, cls.db_format_query( query, values )))
                    time.sleep(timeout)
                
                else:
                    log.exception(oe)
                    log.error("FATAL: failed to execute query (%s, %s)" % (query, values))
                    log.error("\n".join(traceback.format_stack()))
                    os.abort()

            except Exception, e:
                log.exception(e)
                log.error("FATAL: failed to execute query (%s, %s)" % (query, values))
                log.error("\n".join(traceback.format_stack()))
                os.abort() 
Example #12
Source File: shutdown_test.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def test_async_terminate_abort(self):
    os.abort()
    self.mox.ReplayAll()
    shutdown._async_terminate()
    self.assertTrue(shutdown._shutting_down)
    shutdown._async_terminate()
    shutdown._async_terminate()
    self.mox.VerifyAll() 
Example #13
Source File: macro.py    From magics-python with Apache License 2.0 5 votes vote down vote up
def inspect(self):
        cmd = (
            'odbsql -q "'
            + self.args["query"]
            + '" -i '
            + self.args["path"]
            + " -o data.ascii"
        )
        if os.system(cmd):
            print("Error in filtering ODB data... Aborting")
            os.abort()
        cmd = os.environ["ODB_REPORTER"] + " %s" % "data.ascii"
        if os.system(cmd):
            print("Error in viewing ODB data... Aborting")
            os.abort() 
Example #14
Source File: test_subprocess.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_run_abort(self):
        # returncode handles signal termination
        with _SuppressCoreFiles():
            p = subprocess.Popen([sys.executable, "-c",
                                  "import os; os.abort()"])
            p.wait()
        self.assertEqual(-p.returncode, signal.SIGABRT) 
Example #15
Source File: __init__.py    From abseil-py with Apache License 2.0 5 votes vote down vote up
def emit(self, record):
    """Prints a record out to some streams.

    If FLAGS.logtostderr is set, it will print to sys.stderr ONLY.
    If FLAGS.alsologtostderr is set, it will print to sys.stderr.
    If FLAGS.logtostderr is not set, it will log to the stream
      associated with the current thread.

    Args:
      record: logging.LogRecord, the record to emit.
    """
    # People occasionally call logging functions at import time before
    # our flags may have even been defined yet, let alone even parsed, as we
    # rely on the C++ side to define some flags for us and app init to
    # deal with parsing.  Match the C++ library behavior of notify and emit
    # such messages to stderr.  It encourages people to clean-up and does
    # not hide the message.
    level = record.levelno
    if not FLAGS.is_parsed():  # Also implies "before flag has been defined".
      global _warn_preinit_stderr
      if _warn_preinit_stderr:
        sys.stderr.write(
            'WARNING: Logging before flag parsing goes to stderr.\n')
        _warn_preinit_stderr = False
      self._log_to_stderr(record)
    elif FLAGS['logtostderr'].value:
      self._log_to_stderr(record)
    else:
      super(PythonHandler, self).emit(record)
      stderr_threshold = converter.string_to_standard(
          FLAGS['stderrthreshold'].value)
      if ((FLAGS['alsologtostderr'].value or level >= stderr_threshold) and
          self.stream != sys.stderr):
        self._log_to_stderr(record)
    # Die when the record is created from ABSLLogger and level is FATAL.
    if _is_absl_fatal_record(record):
      self.flush()  # Flush the log before dying.

      # In threaded python, sys.exit() from a non-main thread only
      # exits the thread in question.
      os.abort() 
Example #16
Source File: logging_functional_test.py    From abseil-py with Apache License 2.0 5 votes vote down vote up
def _verify_fatal(status, output):
  """Check that helper died as expected."""
  # os.abort generates a SIGABRT signal (-6). On Windows, the process
  # immediately returns an exit code of 3.
  # See https://docs.python.org/3.6/library/os.html#os.abort.
  expected_exit_code = 3 if os.name == 'nt' else -6
  _verify_status(expected_exit_code, status, output) 
Example #17
Source File: shutdown.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def _async_terminate(*_):
  async_quit()
  global _num_terminate_requests
  _num_terminate_requests += 1
  if _num_terminate_requests == 1:
    logging.info('Shutting down.')
  if _num_terminate_requests >= 3:
    logging.error('Received third interrupt signal. Terminating.')
    os.abort() 
Example #18
Source File: shutdown_test.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    self.mox = mox.Mox()
    self.mox.StubOutWithMock(os, 'abort')
    shutdown._shutting_down = False
    shutdown._num_terminate_requests = 0
    self._sigint_handler = signal.getsignal(signal.SIGINT)
    self._sigterm_handler = signal.getsignal(signal.SIGTERM) 
Example #19
Source File: shutdown_test.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    self.mox = mox.Mox()
    self.mox.StubOutWithMock(os, 'abort')
    shutdown._shutting_down = False
    shutdown._num_terminate_requests = 0
    self._sigint_handler = signal.getsignal(signal.SIGINT)
    self._sigterm_handler = signal.getsignal(signal.SIGTERM) 
Example #20
Source File: test_subprocess.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_run_abort(self):
        # returncode handles signal termination
        with support.SuppressCrashReport():
            p = subprocess.Popen([sys.executable, "-c",
                                  'import os; os.abort()'])
            p.wait()
        self.assertEqual(-p.returncode, signal.SIGABRT) 
Example #21
Source File: test_subprocess.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_run_abort(self):
            # returncode handles signal termination
            old_limit = self._suppress_core_files()
            try:
                p = subprocess.Popen([sys.executable,
                                      "-c", "import os; os.abort()"])
            finally:
                self._unsuppress_core_files(old_limit)
            p.wait()
            self.assertEqual(-p.returncode, signal.SIGABRT) 
Example #22
Source File: test_subprocess.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_run_abort(self):
            # returncode handles signal termination
            old_limit = self._suppress_core_files()
            try:
                p = subprocess.Popen([sys.executable,
                                      "-c", "import os; os.abort()"])
            finally:
                self._unsuppress_core_files(old_limit)
            p.wait()
            self.assertEqual(-p.returncode, signal.SIGABRT) 
Example #23
Source File: test_subprocess.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_run_abort(self):
            # returncode handles signal termination
            old_limit = self._suppress_core_files()
            try:
                p = subprocess.Popen([sys.executable,
                                      "-c", "import os; os.abort()"])
            finally:
                self._unsuppress_core_files(old_limit)
            p.wait()
            self.assertEqual(-p.returncode, signal.SIGABRT) 
Example #24
Source File: vsctl.py    From ryu with Apache License 2.0 5 votes vote down vote up
def not_reached():
    os.abort() 
Example #25
Source File: test_stdconsole.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_os_abort(self):
        # Positive
        self.TestCommandLine(("-c", "import os; os.abort()"), "", 1)
        self.TestScript((), "import os\nos.abort()", "", 1) 
Example #26
Source File: virtualchain.py    From virtualchain with GNU General Public License v3.0 5 votes vote down vote up
def sync_virtualchain(blockchain_opts, last_block, state_engine, expected_snapshots={}, tx_filter=None ):
    """
    Synchronize the virtual blockchain state up until a given block.

    Obtain the operation sequence from the blockchain, up to and including last_block.
    That is, go and fetch each block we haven't seen since the last call to this method,
    extract the operations from them, and record in the given working_dir where we left
    off while watching the blockchain.

    Store the state engine state, consensus snapshots, and last block to the working directory.
    Return True on success
    Return False if we're supposed to stop indexing
    Abort the program on error.  The implementation should catch timeouts and connection errors
    """

    rc = False
    start = datetime.datetime.now()
    while True:
        try:

            # advance state
            rc = indexer.StateEngine.build(blockchain_opts, last_block + 1, state_engine, expected_snapshots=expected_snapshots, tx_filter=tx_filter )
            break
        
        except Exception, e:
            log.exception(e)
            log.error("Failed to synchronize chain; exiting to safety")
            os.abort() 
Example #27
Source File: test_stdconsole.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_os_abort(self):
        # Positive
        self.TestCommandLine(("-c", "import os; os.abort()"), "", 1)
        self.TestScript((), "import os\nos.abort()", "", 1) 
Example #28
Source File: test_subprocess.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_run_abort(self):
        # returncode handles signal termination
        with _SuppressCoreFiles():
            p = subprocess.Popen([sys.executable, "-c",
                                  "import os; os.abort()"])
            p.wait()
        self.assertEqual(-p.returncode, signal.SIGABRT) 
Example #29
Source File: shutdown_test.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def test_async_terminate_abort(self):
    os.abort()
    self.mox.ReplayAll()
    shutdown._async_terminate()
    self.assertTrue(shutdown._shutting_down)
    shutdown._async_terminate()
    shutdown._async_terminate()
    self.mox.VerifyAll() 
Example #30
Source File: shutdown.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def _async_terminate(*_):
  async_quit()
  global _num_terminate_requests
  _num_terminate_requests += 1
  if _num_terminate_requests == 1:
    logging.info('Shutting down.')
  if _num_terminate_requests >= 3:
    logging.error('Received third interrupt signal. Terminating.')
    os.abort()