def do_onecam(i, offset_ms,iterator):
time.sleep(offset_ms/1000.0)
print("Time = %f ms : Capturing camera num %d" % (offset_ms, i))
# TODO: run the camera capture code
filename = "/media/ubuntu/VRcameraSSD/tmp/cam%d.%d" % (i,iterator)
p = subprocess.Popen(
["sudo", "./snapshot", filename, "--dev", ("/dev/still%d" % i), "--format", "jpg", "--size", str(4192), str(3104), "--suspend", "--resume"],
stdout=subprocess.PIPE)
try:
(output, err) = p.communicate(timeout=30)
output_str = output.decode("utf-8")
if re.search(r"\*FULL\*", output_str, flags=re.MULTILINE):
print("OK")
elif re.search(r"\*INCOMPLETE\*", output_str, flags=re.MULTILINE):
print("INCOMPLETE")
else:
print("*** FAILED ***")
print("Kernel log:")
#print(get_kern_log(10))
except subprocess.TimeoutExpired:
print("TIMEOUT")
python类TimeoutExpired()的实例源码
def test_all_cameras(numCams, width, height):
for i in range(0, numCams):
print(" cam %d : " % i, end="")
p = subprocess.Popen(
["sudo", "./snapshot", "/dev/null", "--dev", ("/dev/still%d" % i), "--format", "none", "--size", str(width), str(height), "--suspend", "--resume"],
stdout=subprocess.PIPE)
try:
(output, err) = p.communicate(timeout=30)
output_str = output.decode("utf-8")
if re.search(r"\*FULL\*", output_str, flags=re.MULTILINE):
print("OK")
elif re.search(r"\*INCOMPLETE\*", output_str, flags=re.MULTILINE):
print("INCOMPLETE")
else:
print("*** FAILED ***")
print("Kernel log:")
print(get_kern_log(10))
except subprocess.TimeoutExpired:
print("TIMEOUT")
# Read an image from each camera and save it to disk.
def do_onecam(i, offset_ms):
time.sleep(offset_ms/1000.0)
print("Time = %f ms : Capturing camera num %d" % (offset_ms, i))
# TODO: run the camera capture code
filename = "/media/ubuntu/VRcameraSSD/tmp/cam%d.yuyv" % (i)
p = subprocess.Popen(
["sudo", "./snapshot", filename, "--dev", ("/dev/still%d" % i), "--format", "yuyv", "--size", str(4192), str(3104), "--suspend", "--resume"],
stdout=subprocess.PIPE)
try:
(output, err) = p.communicate(timeout=30)
output_str = output.decode("utf-8")
if re.search(r"\*FULL\*", output_str, flags=re.MULTILINE):
print("OK")
elif re.search(r"\*INCOMPLETE\*", output_str, flags=re.MULTILINE):
print("INCOMPLETE")
else:
print("*** FAILED ***")
print("Kernel log:")
#print(get_kern_log(10))
except subprocess.TimeoutExpired:
print("TIMEOUT")
def exec_shell_command( self, command ):
output = None
try:
output = subprocess.check_output( command, shell=True, timeout=50 )
output = output.strip().decode('utf-8')
except subprocess.CalledProcessError:
""" _LOGGER.error("Command failed: %s", command)"""
self.value = CONST_STATE_ERROR
output = None
except subprocess.TimeoutExpired:
""" _LOGGER.error("Timeout for command: %s", command)"""
self.value = CONST_STATE_ERROR
output = None
if output == None:
_LOGGER.error( "Life360 has not responsed well. Nothing to worry, will try again!" )
self.value = CONST_STATE_ERROR
return None
else:
return output
def wait_for_active_job(signal_to_send=None):
"""
Wait for the active job to finish, to be killed by SIGINT, or to be
suspended by ctrl-z.
"""
_clear_dead_jobs()
act = builtins.__xonsh_active_job__
if act is None:
return
job = builtins.__xonsh_all_jobs__[act]
obj = job['obj']
if job['bg']:
return
while obj.returncode is None:
try:
obj.wait(0.01)
except TimeoutExpired:
pass
except KeyboardInterrupt:
obj.kill()
if obj.poll() is not None:
builtins.__xonsh_active_job__ = None
def test_cmd_spawning(self):
env = os.environ.copy()
env["PROXY_API_TOKEN"] = "dummy_token"
path = fixtures.get("remoteappmanager_config.py")
self.spawner.config_file_path = path
args = self.spawner.get_args()
try:
with self.assertRaises(subprocess.TimeoutExpired):
subprocess.check_output(
self.spawner.cmd + args,
timeout=2,
env=env,
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as exc:
print("Output of the command:\n\n{}".format(
exc.output.decode(sys.getdefaultencoding())))
raise
def exec_shell_command( self, command ):
output = None
try:
output = subprocess.check_output( command, shell=True, timeout=60 )
output = output.strip().decode('utf-8')
except subprocess.CalledProcessError:
""" _LOGGER.error("Command failed: %s", command)"""
self.value = CONST_STATE_ERROR
output = None
except subprocess.TimeoutExpired:
""" _LOGGER.error("Timeout for command: %s", command)"""
self.value = CONST_STATE_ERROR
output = None
if output == None:
_LOGGER.error( "Life360 has not responsed well. Nothing to worry, will try again!" )
self.value = CONST_STATE_ERROR
return None
else:
return output
def test_communicate_timeout(self):
p = subprocess.Popen([sys.executable, "-c",
'import sys,os,time;'
'sys.stderr.write("pineapple\\n");'
'time.sleep(1);'
'sys.stderr.write("pear\\n");'
'sys.stdout.write(sys.stdin.read())'],
universal_newlines=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
timeout=0.3)
# Make sure we can keep waiting for it, and that we get the whole output
# after it completes.
(stdout, stderr) = p.communicate()
self.assertEqual(stdout, "banana")
self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
def test_communicate_timeout_large_ouput(self):
# Test an expiring timeout while the child is outputting lots of data.
p = subprocess.Popen([sys.executable, "-c",
'import sys,os,time;'
'sys.stdout.write("a" * (64 * 1024));'
'time.sleep(0.2);'
'sys.stdout.write("a" * (64 * 1024));'
'time.sleep(0.2);'
'sys.stdout.write("a" * (64 * 1024));'
'time.sleep(0.2);'
'sys.stdout.write("a" * (64 * 1024));'],
stdout=subprocess.PIPE)
self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
(stdout, _) = p.communicate()
self.assertEqual(len(stdout), 4 * 64 * 1024)
# Test for the fd leak reported in http://bugs.python.org/issue2791.
def run_subprocess(cinput, invoke, universal_newlines=True, **kwargs):
process = subprocess.Popen(invoke, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=universal_newlines, **kwargs)
try:
result = process.communicate(input=cinput, timeout=60)[0]
except subprocess.TimeoutExpired:
process.kill()
result = "Sorry, your code took too long to run!"
partial_out = process.communicate()[0] # communicate returns a tuple first element is stdout second is stderr
if partial_out:
result += "\nPartial output:\n" + partial_out
except:
traceback.print_exc()
result = "There was an issue running your code."
return result
#temporary workaround while TIO is bugged
def process(self, cmd=[], input=None, timeout=None):
proc = subprocess.Popen(cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.logger.info('Running process, pid=%d: %s' % (proc.pid, str(cmd)))
try:
output, err = proc.communicate(input, timeout=timeout)
except subprocess.TimeoutExpired as e:
self.logger.warning(
'Process %d killed with timeout %s' % (proc.pid, str(timeout)))
proc.kill()
output, err = proc.communicate()
self.logger.debug("stdout: " + repr(output))
self.logger.debug("stderr: " + repr(err))
stdout = output.decode('utf-8')
stderr = err.decode('utf-8')
if proc.returncode != 0:
self.logger.warning(
'Process %d failed with rcode %d' % (proc.pid, int(proc.returncode)))
else:
self.logger.debug('Process %d finished with rcode 0' % (proc.pid))
return int(proc.returncode), stdout, stderr
def run_cmd(self, cmd):
""" run a mpd control command """
call = ["mpc"]
if self.host:
call.extend(["--host", self.host])
if self.port:
call.extend(["--port", self.port])
call.append(cmd)
proc = subprocess.Popen(call, stdout=subprocess.PIPE)
output, _ = proc.communicate()
try:
proc.wait(1)
except subprocess.TimeoutExpired:
raise Exception("mpc doesn't terminate!")
return output
def _wait_for_containers_exit_status(self, containers):
"""Wait for all of the specified containers to exit
and return their exit codes.
Args:
containers (list of str): The containers to wait to exit.
Returns:
list of int: The list of return codes for the process in each
container.
"""
wait = ['docker', 'wait'] + containers
handle = subprocess.Popen(
args=wait,
stdout=subprocess.PIPE,
universal_newlines=True)
try:
output, _ = handle.communicate(timeout=35)
return [int(e) for e in output.strip().split('\n')]
except subprocess.TimeoutExpired:
handle.kill()
LOGGER.warning("Docker timed out waiting for %s to exit",
containers)
return []
def rm(filename, sudo=False):
"""
Remove a file on the disk, not us os.rm because we want to add timeout to
the command. It's possible that the os call got hang when the disk has
some problems
"""
cmd_args = []
if sudo:
cmd_args += ['sudo']
cmd_args += ['/bin/rm', filename]
log.debug("Executing cmd: {}".format(str(cmd_args)))
proc = subprocess.Popen(cmd_args, stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
try:
(stdout, stderr) = proc.communicate(timeout=10)
except subprocess.TimeoutExpired:
proc.kill()
raise OSCError('SHELL_TIMEOUT', {'cmd': ' '.join(cmd_args)})
def update_pools(self):
# designate-manage communicates with designate via message bus so no
# need to set OS_ vars
# NOTE(AJK) this runs with every hook (once most relations are up) and
# so if it fails it will be picked up by the next relation change or
# update-status. i.e. it will heal eventually.
if hookenv.is_leader():
try:
cmd = "designate-manage pool update"
# Note(tinwood) that this command may fail if the pools.yaml
# doesn't actually contain any pools. This happens when the
# relation is broken, which errors out the charm. This stops
# this happening and logs the error.
subprocess.check_call(cmd.split(), timeout=60)
except subprocess.CalledProcessError as e:
hookenv.log("designate-manage pool update failed: {}"
.format(str(e)))
except subprocess.TimeoutExpired as e:
# the timeout is if the rabbitmq server has gone away; it just
# retries continuously; this lets the hook complete.
hookenv.log("designate-manage pool command timed out: {}".
format(str(e)))
def test_run_script_timed_out_script(self):
scripts_dir = self.useFixture(TempDirectory()).path
script = make_script(scripts_dir=scripts_dir)
self.mock_capture_script_output.side_effect = TimeoutExpired(
[factory.make_name('arg') for _ in range(3)],
script['timeout_seconds'])
self.args.pop('status')
self.assertFalse(run_script(script, scripts_dir))
self.assertThat(self.mock_output_and_send, MockCallsMatch(
call(
'Starting %s' % script['msg_name'], status='WORKING',
**self.args),
call(
'Timeout(%s) expired on %s' % (
str(timedelta(seconds=script['timeout_seconds'])),
script['msg_name']),
files={
script['combined_name']: script['combined'].encode(),
script['stdout_name']: script['stdout'].encode(),
script['stderr_name']: script['stderr'].encode(),
script['result_name']: script['result'].encode(),
}, status='TIMEDOUT', **self.args),
))
def _terminate_process(process, wait=2.5, kill=2.5):
"""Ensures that `process` terminates.
:return: The exit code of the process.
"""
try:
# The subprocess may have already been signalled, for example as part
# of this process's process group when Ctrl-c is pressed at the
# terminal, so give it some time to exit.
return process.wait(timeout=wait)
except subprocess.TimeoutExpired:
# Either the subprocess has not been signalled, or it's slow.
process.terminate() # SIGTERM.
try:
return process.wait(timeout=kill)
except subprocess.TimeoutExpired:
process.kill() # SIGKILL.
return process.wait()
def install(server,*,eula=False):
if not os.path.isdir(server.data["dir"]):
os.makedirs(server.data["dir"])
mcjar=os.path.join(server.data["dir"],server.data["exe_name"])
if not os.path.isfile(mcjar):
raise ServerError("Can't find server jar ({}). Please place the files in the directory and/or update the 'exe_name' then run setup again".format(mcjar))
server.data.save()
eulafile=os.path.join(server.data["dir"],"eula.txt")
configfile=os.path.join(server.data["dir"],"server.properties")
if not os.path.isfile(configfile) or (eula and not os.path.isfile(eulafile)): # use as flag for has the server created it's files
print("Starting server to create settings")
try:
ret=sp.check_call(["java","-jar",server.data["exe_name"],"nogui"],cwd=server.data["dir"],shell=False,timeout=20)
except sp.CalledProcessError as ex:
print("Error running server. Java returned status: "+ex.returncode)
except sp.TimeoutExpired as ex:
print("Error running server. Process didn't complete in time")
updateconfig(configfile,{"server-port":str(server.data["port"])})
if eula:
updateconfig(eulafile,{"eula":"true"})