Here is an example for a smart time-out implementation. It is particularily needed, if sub-shells are involved.
#!/usr/bin/env python
import subprocess, time, sys
class Timeout(Exception): pass
def run(command, timeout=10):
”'
code by flybywire, stackoverflow
”'
proc = subprocess.Popen(command, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
poll_seconds = .250
deadline = time.time()+timeout
while time.time() < deadline and proc.poll() == None:
time.sleep(poll_seconds)
if proc.poll() == None:
if float(sys.version[:3]) >= 2.6:
proc.terminate()
raise Timeout()
stdout, stderr = proc.communicate()
return stdout, stderr, proc.returncode
def doCheckHost( host):
”'
we execute some command on a remote host and capture the output.
Since hosts may not reply, we need a time-out. The usual time-out
implementation (signal, alarm()) does not work for Popen()
”'
com = [ "stat", "--format='%Y'", "/online_dir/TangoDump.lis"]
try:
lst = run( com, timeout = 3)
except Exception as e:
print( "Time-out for ", host)
return None
return lst
def main():
for host in ['haspp98', 'haspp99']:
res = doCheckHost( host)
print( "%s: %s" % (host, res))
if __name__ == '__main__':
main()