本文整理汇总了Python中signal.alarm函数的典型用法代码示例。如果您正苦于以下问题:Python alarm函数的具体用法?Python alarm怎么用?Python alarm使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了alarm函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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
示例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)
示例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())
示例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)
示例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
示例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)
示例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
示例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
示例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()
示例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))
示例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)
示例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)
示例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)
示例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()