• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python signal.alarm函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中signal.alarm函数的典型用法代码示例。如果您正苦于以下问题:Python alarm函数的具体用法?Python alarm怎么用?Python alarm使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了alarm函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: run

def run(args, input=None, cwd = None, shell = False, kill_tree = True, timeout = -1, env = None):
    '''
    Run a command with a timeout after which it will be forcibly
    killed.
    '''
    class Alarm(Exception):
        pass
    def alarm_handler(signum, frame):
        raise Alarm
    p = Popen(args, shell = shell, cwd = cwd, stdout = PIPE, stderr = PIPE, env = env)
    if timeout != -1:
        if alarm_available:
            signal(SIGALRM, alarm_handler)
        alarm(timeout)
    try:
        t0 = time.time()
        stdout, stderr = p.communicate()
        print("Ran for", time.time()-t0, "seconds.")
        if timeout != -1:
            alarm(0)
    except Alarm:
        pids = [p.pid]
        if kill_tree:
            pids.extend(get_process_children(p.pid))
        for pid in pids:
            # process might have died before getting to this line
            # so wrap to avoid OSError: no such process
            try:
                kill(pid, SIGKILL)
            except OSError:
                pass
        return -9, '', ''
    return p.returncode, stdout, stderr
开发者ID:andrescodas,项目名称:casadi,代码行数:33,代码来源:testsuite.py


示例2: local

def local(cmd, retry_ttl=0, retry_interval=3, capture=True, timeout=60, **kwargs):
    def retry(*args, **kwargs):
        log.info('failed cmd: {0}, ttl: {1}, sleep: {2}'.format(
            cmd, retry_ttl, retry_interval))
        if retry_ttl > 0:
            time.sleep(retry_interval)
            local(cmd, retry_ttl - 1, retry_interval, capture)

    log_cmd = 'local> ' + cmd
    api.env.cmd_history.append(log_cmd)
    log.info(log_cmd)
    print_for_test(log_cmd)

    if api.env.is_test:
        result = test_cmd(cmd)
    else:
        signal.signal(signal.SIGALRM, retry)
        signal.alarm(timeout)
        try:
            result = api.local(cmd, capture=capture, **kwargs)
        finally:
            signal.alarm(0)

    result_msg = 'return> {0}'.format(result.return_code)
    log.info(result_msg)
    print_for_test(result_msg)

    return result
开发者ID:fabrickit,项目名称:fabkit,代码行数:28,代码来源:base.py


示例3: kill_workers

    def kill_workers(self, timeout=5):
        """
        Send a suicide message to all workers, with some kind of timeout.
        """
        logging.info('Killing workers, taking up to %d seconds.', int(timeout))
        poller = zmq.Poller()
        poller.register(self.results_pull, zmq.POLLIN)

        while True:
            # Seems to get stuck gevent-blocking in the work_push.send() after
            # all the workers have died.  Also, gevent.Timeout() doesn't seem
            # to work here?!
            signal.alarm(int(timeout))
            self.work_push.send(msgpack.dumps([{'type': 'PING'}]))
            socks = dict(poller.poll(timeout * 1500))
            if self.results_pull in socks \
                    and socks[self.results_pull] == zmq.POLLIN:
                result_packed = self.results_pull.recv()
                result = msgpack.loads(result_packed)
                logging.info('Heard from worker id=%d; sending SUICIDE',
                            result['worker_id'])
                self.work_push.send(msgpack.dumps([{'type': 'SUICIDE'}]))
                gevent.sleep(0.1)
            else:
                break
            signal.alarm(0)
开发者ID:WIZARD-CXY,项目名称:ssbench,代码行数:26,代码来源:master.py


示例4: run

    def run(self):
        class Alarm(Exception):
            pass
        def alarm_handler(signum, frame):
            raise Alarm

        try:
            self.process = Popen(self.args, shell=True, stdout=PIPE, stderr=PIPE)
            if self.timeout != -1:
                signal(SIGALRM, alarm_handler)
                alarm(self.timeout)

            try:
                self.stdout, self.stderr = self.process.communicate()
                if self.timeout != -1:
                    alarm(0)
            except Alarm:
                os.kill(self.process.pid, SIGKILL)
                raise  CloudRuntimeException("Timeout during command execution")

            self.success = self.process.returncode == 0
        except:
            raise  CloudRuntimeException(formatExceptionInfo())

        if not self.success: 
            logging.debug("Failed to execute:" + self.getErrMsg())
开发者ID:anshulgangwar,项目名称:incubator-cloudstack,代码行数:26,代码来源:utilities.py


示例5: timeLimit

def timeLimit(seconds):
    """
    http://stackoverflow.com/a/601168
    Use to limit the execution time of a function. Raises an exception if the execution of the
    function takes more than the specified amount of time.

    :param seconds: maximum allowable time, in seconds
    >>> import time
    >>> with timeLimit(5):
    ...    time.sleep(4)
    >>> import time
    >>> with timeLimit(5):
    ...    time.sleep(6)
    Traceback (most recent call last):
        ...
    RuntimeError: Timed out
    """
    def signal_handler(signum, frame):
        raise RuntimeError('Timed out')

    signal.signal(signal.SIGALRM, signal_handler)
    signal.alarm(seconds)
    try:
        yield
    finally:
        signal.alarm(0)
开发者ID:HPCBio,项目名称:toil,代码行数:26,代码来源:__init__.py


示例6: set_continuous_command

 def set_continuous_command(self, command):
     # The command sent to the IMU will be result in a continuous data stream
     signal.alarm(TIMEOUT_SECS)
     try:
         self.packet = []
         self.send_byte(0x10)
         self.send_byte(0x00)
         self.send_byte(command)
         self.current_command = command
         # setting a continuous command will send back a 7 byte response
         self.packet = list(self.ser.read(7))
         # read back the packet and make sure it is correct by parsing else return false
         if not self.parse_packet(7):
             if DEBUG:
                 print("failed setting command")
             return False
         else:
             if DEBUG:
                 print("successly set command!:")
     except IOError:
         print("cannot write and set to continuous mode")
         return False
     except Timeout:
         return False
     signal.alarm(0)
     return True
开发者ID:viron11111,项目名称:PropaGator,代码行数:26,代码来源:micro_3dm_gx1.py


示例7: testInterruptedTimeout

 def testInterruptedTimeout(self):
     # XXX I don't know how to do this test on MSWindows or any other
     # plaform that doesn't support signal.alarm() or os.kill(), though
     # the bug should have existed on all platforms.
     if not hasattr(signal, "alarm"):
         return                  # can only test on *nix
     self.serv.settimeout(5.0)   # must be longer than alarm
     class Alarm(Exception):
         pass
     def alarm_handler(signal, frame):
         raise Alarm
     old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
     try:
         signal.alarm(2)    # POSIX allows alarm to be up to 1 second early
         try:
             foo = self.serv.accept()
         except socket.timeout:
             self.fail("caught timeout instead of Alarm")
         except Alarm:
             pass
         except:
             self.fail("caught other exception instead of Alarm")
         else:
             self.fail("nothing caught")
         signal.alarm(0)         # shut off alarm
     except Alarm:
         self.fail("got Alarm in wrong place")
     finally:
         # no alarm can be pending.  Safe to restore old handler.
         signal.signal(signal.SIGALRM, old_alarm)
开发者ID:249550148,项目名称:gevent,代码行数:30,代码来源:test_socket.py


示例8: fork_and_check

def fork_and_check(constr):
  constr = simplify(constr)

  parent_conn, child_conn = multiprocessing.Pipe()
  p = multiprocessing.Process(target=fork_and_check_worker,
                              args=(constr, child_conn))
  p.start()
  child_conn.close()

  ## timeout after a while..
  def sighandler(signo, stack):
    print "Timed out.."
    # print z3expr(constr, True).sexpr()
    p.terminate()

  signal.signal(signal.SIGALRM, sighandler)
  signal.alarm(z3_timeout)

  try:
    res = parent_conn.recv()
  except EOFError:
    res = (z3.unknown, None)
  finally:
    signal.alarm(0)

  p.join()
  return res
开发者ID:ukk1,项目名称:ITKST53,代码行数:27,代码来源:fuzzy.py


示例9: run

    def run(js, testfile):
        if "%s" in js:
          cmd = js.replace("%s", testfile)
        else:
          cmd = js+" "+testfile

        class TimeException(Exception):
            pass

        def timeout_handler(signum, frame):
            raise TimeException()

        signal.signal(signal.SIGALRM, timeout_handler) 
        signal.alarm(2) # triger alarm in 3 seconds

        try:
            proc = subprocess.Popen(  cmd, shell=True,
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE)
            output, error = proc.communicate('through stdin to stdout')
            signal.alarm(0)
            return error+output
        except TimeException:
            #os.kill(proc.pid+1, signal.SIGINT) # no idea why + 1, but the reported pid isn't right ?!
            subprocess.Popen("killall js", shell=True)
            return -1
开发者ID:DeveloperVox,项目名称:tools,代码行数:26,代码来源:Reducer.py


示例10: start

 def start(self):
     if self.with_signaling:
         signal.signal(signal.SIGALRM, self.murder_connections)
         signal.alarm(self.timeout)
     else:
         self._reaper = ConnectionReaper(self, delay=self.timeout)
         self._reaper.ensure_started()
开发者ID:ronnix,项目名称:restkit,代码行数:7,代码来源:base.py


示例11: run

    def run(self, command, interpreter="/bin/bash", forward_ssh_agent=False):
        """
        Execute ``command`` using ``interpreter``

        Consider this roughly as::

            echo "command" | ssh [email protected] "/bin/interpreter"

        Raise SSHError if server is unreachable

        Hint: Try interpreter='/usr/bin/python'
        """
        ssh_command = self.ssh_command(interpreter, forward_ssh_agent)
        pipe = subprocess.Popen(
            ssh_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=self.get_env()
        )
        try:
            signal.signal(signal.SIGALRM, _timeout_handler)
        except ValueError:  # signal only works in main thread
            pass
        signal.alarm(self.timeout)
        out = err = ""
        try:
            out, err = pipe.communicate(command)
        except IOError, exc:
            # pipe.terminate() # only in python 2.6 allowed
            os.kill(pipe.pid, signal.SIGTERM)
            signal.alarm(0)  # disable alarm
            raise SSHError(str(exc))
开发者ID:frog32,项目名称:openssh-wrapper,代码行数:29,代码来源:openssh_wrapper.py


示例12: write_dot_graph

def write_dot_graph(filename, dot_graph,
                    run_graphviz=True,
                    quiet=False,
                    timeout=DEFAULT_TIMEOUT):
    """
    Write a dot graph and possibly run graphviz on it
    """
    makedirs(fp.dirname(filename))
    dot_file = filename + '.dot'
    svg_file = filename + '.svg'
    with codecs.open(dot_file, 'w', encoding='utf-8') as dotf:
        print(dot_graph.to_string(), file=dotf)
    if run_graphviz:
        if not quiet:
            print("Creating %s" % svg_file, file=sys.stderr)
        signal.signal(signal.SIGALRM, alarm_handler)
        signal.alarm(timeout)  # half a minute
        try:
            subprocess.call(["dot",
                             "-T", "svg",
                             "-o", svg_file,
                             dot_file])
            signal.alarm(0)  # reset the alarm
        except Alarm:
            print("Killed graphviz because it was taking too long",
                  file=sys.stderr)
开发者ID:eipiplusun,项目名称:attelo,代码行数:26,代码来源:graph.py


示例13: __init__

 def __init__(self, alarm_time = 1, silent = False):
     self.running_thread = []
     self.paused_thread = []
     self.alarm_time = alarm_time
     self.silent = silent
     signal.signal(signal.SIGALRM, self)
     signal.alarm(self.alarm_time)
开发者ID:Aubreymcfato,项目名称:phetools,代码行数:7,代码来源:task_scheduler.py


示例14: playback

def playback(refdes, event_url, particle_url, missing_dates):
    """
    Put together the directory glob and other options for the playback command.
    This will then playback cabled data.
    """
    main_directory = '/rsn_cabled/rsn_data/DVT_Data'
    driver = get_driver(refdes)
    reader_list = get_reader_type(refdes)
    node = refdes.split('-')[1].lower()
    instrument = refdes.split('-')[3]
    signal.signal(signal.SIGALRM, timeout_handler)

    for reader in reader_list:
        for date in missing_dates:
            directory = '/'.join([main_directory, node, instrument])
            directory += '*'.join(['', date, ''])

            # Check to see if this particular file exists before executing callback
            if glob.glob(directory):
                playback_command = ' '.join(['playback', reader, driver, refdes, event_url, particle_url, directory])
                logging.info("%s", playback_command)

                # Some playback reader types may not ingest the data at all.
                # Timeout after 90 seconds and continue to the next reader type or
                # next data.
                signal.alarm(90)    
                try:
                    call(playback_command, shell=True)
                except TimeoutException:
                    logging.warning('%s Took more than 90 seconds. Timing out this ingestion.', playback_command)
                    continue 
                else:
                    signal.alarm(0)
开发者ID:ooi-integration,项目名称:ingestion-csvs,代码行数:33,代码来源:ingest_missing.py


示例15: reap

 def reap(self):
   """Collect the dead jobs."""
   while self._running:
     dead = set()
     for job in self._running:
       st = job.state(self._cache)
       if st == _RUNNING: continue
       if st == _FAILURE or st == _KILLED:
         self._failures += 1
         if self._stop_on_failure:
           self._cancelled = True
           for job in self._running:
             job.kill()
       dead.add(job)
       break
     for job in dead:
       self._completed += 1
       self._running.remove(job)
     if dead: return
     if (not self._travis):
       message('WAITING', '%d jobs running, %d complete, %d failed' % (
           len(self._running), self._completed, self._failures))
     if platform.system() == 'Windows':
       time.sleep(0.1)
     else:
       global have_alarm
       if not have_alarm:
         have_alarm = True
         signal.alarm(10)
       signal.pause()
开发者ID:quirkey,项目名称:grpc,代码行数:30,代码来源:jobset.py


示例16: timeout_call_old

def timeout_call_old(cmd, timeout):
    """ Invokes command specified by @cmd. 
        Raises 'Alarm' Exception if cmd does
        not return withint @timeout (in secs)
        
        Can only be used in main thread ;-(
    """
    call = None

    def timeout_handler(signum, frame):
        if call:
            os.kill(call.pid, signal.SIGKILL)
            os.waitpid(-1, os.WNOHANG)
        raise Alarm

    signal.signal(signal.SIGALRM, timeout_handler)

    call = subprocess.Popen(cmd,
            shell = True, close_fds = True,
            stdout = subprocess.PIPE,
            stderr = subprocess.PIPE)

    signal.alarm(timeout)
    res = call.communicate()
    return_code = call.returncode
    signal.alarm(0) # switch off alarm
    return res, return_code
开发者ID:placiflury,项目名称:gridmonitor-sft,代码行数:27,代码来源:helpers.py


示例17: timeout

def timeout(timeout_secs, func, *args, **kwargs):
    """Enforce a maximum time for a callable to complete.
    Not yet implemented on Windows.
    """
    default_return = kwargs.pop('default_return', None)
    if on_win:
        # Why does Windows have to be so difficult all the time? Kind of gets old.
        # Guess we'll bypass Windows timeouts for now.
        try:
            return func(*args, **kwargs)
        except KeyboardInterrupt:  # pragma: no cover
            return default_return
    else:
        class TimeoutException(Exception):
            pass

        def interrupt(signum, frame):
            raise TimeoutException()

        signal.signal(signal.SIGALRM, interrupt)
        signal.alarm(timeout_secs)

        try:
            ret = func(*args, **kwargs)
            signal.alarm(0)
            return ret
        except (TimeoutException,  KeyboardInterrupt):  # pragma: no cover
            return default_return
开发者ID:alanhdu,项目名称:conda,代码行数:28,代码来源:io.py


示例18: test_from_arguments

 def test_from_arguments(self):
     options = Options()
     options.collecting_data = True
     options.display_data = False
     options.filename = '/tmp/%s' % (str(uuid.uuid4()))
     options.file_max_size = 0.01
     options.sample_interval_secs = 1
     self.addCleanup(lambda: os.remove(options.filename))
     signal.signal(signal.SIGALRM, timeout_handler)
     signal.alarm(3)
     try:
         with suppress_stdout():
             # still get the os system clear call which blanks the screen
             main(options)
     except Exception:
         pass
     data = []
     with open(options.filename, 'r') as data_file:
         for line in data_file:
             data.append(json.loads(line))
     self.assertTrue(len(data) > 0)
     self.assertTrue('cpu_times' in data[0])
     self.assertTrue('utc_time' in data[0])
     self.assertTrue('sample_time' in data[0])
     self.assertTrue('num_threads' in data[0])
开发者ID:alex----,项目名称:monpy,代码行数:25,代码来源:test_integration.py


示例19: get_packet

    def get_packet(self, num_bytes):
        # set an alarm to timeout in 5 seconds and signal a PacketTimeout if we have not gotten a full packet
        signal.alarm(TIMEOUT_SECS)
        self.packet = []
        try:
            while True:
                self.packet.append(self.ser.read(1))
                if DEBUG:
                    print("self packet = " + str(self.packet[0]))
                    print("current command = " + str(self.current_command))

                    # if the first value of the packet is not the command byte, pop values off until it is
                if ord(self.packet[0]) != self.current_command and self.packet:
                    self.packet.pop(0)

                    # check if we have enough bytes for a complete packet
                if len(self.packet) >= num_bytes:
                    # try to get a complete packet
                    int_list = self.parse_packet(num_bytes)
                    if int_list:
                        self.good_packets += 1
                        signal.alarm(0)
                        return int_list
                    else:
                        while self.packet and self.packet[0] != self.current_command:
                            # remove values at the head of the packet until you find another potential header
                            self.packet.pop(0)
        except Timeout:
            self.packet = []
            return False
开发者ID:viron11111,项目名称:PropaGator,代码行数:30,代码来源:micro_3dm_gx1.py


示例20: time_limit

def time_limit(seconds):
    """Limit function execution time.

    >>> try:
            with time_limit(10):
                long_function_call()
        except TimeoutException:
            print "Timeout"
    >>>

    Args:
        seconds: An integer indicating how long limit the function
            execution time.

    """

    def signal_handler(signum, frame):
        raise TimeLimitException("timeout")

    signal.signal(signal.SIGALRM, signal_handler)
    signal.alarm(seconds)

    try:
        yield
    finally:
        signal.alarm(0)
开发者ID:yu-liang-kono,项目名称:pdfworker,代码行数:26,代码来源:util.py



注:本文中的signal.alarm函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python signal.getitimer函数代码示例发布时间:2022-05-27
下一篇:
Python sigmoid.sigmoid函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap