本文整理汇总了Python中subprocess.Popen.poll方法的典型用法代码示例。如果您正苦于以下问题:Python Popen.poll方法的具体用法?Python Popen.poll怎么用?Python Popen.poll使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类subprocess.Popen
的用法示例。
在下文中一共展示了Popen.poll方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import poll [as 别名]
def run(target, timeout=TIMEOUT, retry=RETRY,
preserveChildren=False, verbose=False):
"""Run a process but kill it after timeout
@param target: the command to launch (str)
@param timeout: timeout in seconds before start killing process (int)
@param retry: Number of time we will try to kill the process with SIGTERM and SIGKILL (int)
@param preserveChildren: Do we need to also kill process children ? Default is True (bool)
@param verbose: Print what happened on standard output (bool)
@return: 0 if everything is ok. 1 if process was killed, 2 if something goes wrong.
"""
rc=0
# Some sanity checks
if timeout<0 or retry<1:
print "Timeout must be a positive integer and number of retry must be greater or equal than 1"
return 2
if verbose:
print "running %s" % target
process=Popen(target, shell=True)
endTime=time()+timeout
while True:
# Timeout
if time()>endTime:
rc=1
if verbose:
print "Process timeout"
break
# Process finish
if process.poll() is not None:
if verbose:
print "Process finish before timeout"
break
# Wait a little before looping
sleep(0.05)
if process.poll() is not None:
if verbose:
print "process correctly finished"
else:
if preserveChildren:
pids=[]
else:
pids=getChildrenPid(process.pid, verbose)
pids.append(process.pid)
for i in xrange(retry):
for signal in (15, 9): # SIGTERM then SIGKILL
for pid in pids:
if verbose:
print "kill %s with signal %s" % (pid, signal)
try:
os.kill(pid, signal)
except OSError, e:
if e.errno==1:
print "Not authorized to kill %s" % pid
elif e.errno==3:
# No such process - already dead
pass
else:
print "Error while killing %s:\n%s" % (pid, e)
sleep(i)
示例2: testLocal
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import poll [as 别名]
def testLocal(self):
# note: ignore_zero_padding necessary until '0' padding simulation bug is resolved
record = PacketRecord(ignore_zero_padding=True)
# start capture
process = Popen([CLIENT_APP, DFE_IP, DFE_NETMASK, '-l', CAPTURE_FILE], env=self.env, \
stdout=DEV_NULL, stderr=DEV_NULL)
self.processes.append(process)
# send packets
for i in range(PACKET_COUNT):
packet = IP(dst='127.0.0.2')/ICMP()
sendp(packet, iface=self.iface, verbose=False)
record.add_sent(packet)
# wait for stragglers
time.sleep(1)
# make sure still running
process.poll()
self.assertTrue(process.returncode == None)
# stop capture
process.terminate()
# hack: send one more packet to make sure capture closes immediately
sendp(IP(), iface=self.iface, verbose=False)
process.wait()
# verify capture CAPTURE_FILE
for packet in rdpcap(CAPTURE_FILE):
record.add_received(packet)
self.assertTrue(record.verify())
示例3: testBasic
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import poll [as 别名]
def testBasic(self):
iface = self.tap.name
record = PacketRecord()
# start capture
process = Popen([APP, iface, CAPTURE_FILE], stdout=DEV_NULL, stderr=DEV_NULL)
# send packets
for i in range(PACKET_COUNT):
packet = IP(dst="www.google.com")/ICMP()
sendp(packet, iface=iface, verbose=False)
record.add_sent(packet)
# wait for stragglers
time.sleep(1)
# stop capture
process.terminate()
# hack: send one more packet to make sure capture closes immediately
sendp(IP(), iface=iface, verbose=False)
process.poll()
# verify capture file
for packet in rdpcap(CAPTURE_FILE):
record.add_received(packet)
self.assertTrue(record.verify())
示例4: run
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import poll [as 别名]
def run(cmd):
handle = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT)
while handle.poll() is None:
print(handle.stdout.read(1).decode('utf-8'), end='')
print(handle.stdout.read(1).decode('utf-8'), end='') # Last byte, if there is any.
handle.stdout.close()
return handle.poll()
示例5: run_and_capture
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import poll [as 别名]
def run_and_capture(self):
"""
Run a command and capture exceptions. This is a blocking call
:returns: tuple of exitcode, error (or None)
:rtype: int, str | None
"""
subproc = Popen([self._executable, self._command] + self._args,
stderr=PIPE)
err = ''
while subproc.poll() is None:
line = subproc.stderr.readline().decode('utf-8')
err += line
sys.stderr.write(line)
sys.stderr.flush()
exitcode = subproc.poll()
# We only want to catch exceptions, not other stderr messages
# (such as "task does not exist", so we look for the 'Traceback'
# string. This only works for python, so we'll need to revisit
# this in the future when we support subcommands written in other
# languages.
err = ('Traceback' in err and err) or None
return exitcode, err
示例6: test_difftool
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import poll [as 别名]
def test_difftool(git_repo, request):
nbdime.gitdifftool.main(['config', '--enable'])
cmd = get_output('git config --get --local difftool.nbdime.cmd').strip()
# pick a non-random port so we can connect later, and avoid opening a browser
port = 62021
cmd = cmd + ' --port=%i --browser=disabled' % port
call(['git', 'config', 'difftool.nbdime.cmd', cmd])
# avoid global diff driver config from disabling difftool:
with open('.gitattributes', 'w') as f:
f.write('*.ipynb\tdiff=notnbdime')
p = Popen(['git', 'difftool', '--tool=nbdime', 'base'])
def _term():
try:
p.terminate()
except OSError:
pass
request.addfinalizer(_term)
# 3 is the number of notebooks in this diff
url = 'http://127.0.0.1:%i' % port
for i in range(3):
_wait_up(url, check=lambda : p.poll() is None)
# server started
r = requests.get(url + '/difftool')
r.raise_for_status()
# close it
r = requests.post(url + '/api/closetool', headers={'exit_code': '0'})
r.raise_for_status()
time.sleep(0.25)
# wait for exit
p.wait()
assert p.poll() == 0
示例7: _popen
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import poll [as 别名]
def _popen(self, command, timeout, timeout_msg, rc_non_zero_msg, common_msg=""):
""" Runs a command in background and returns its return_code, stdout and stderr.
stdout and stderr will be None if return code = 0
"""
stdout, stderr = None, None
# Run the command
p = Popen(command, stdout=PIPE, stderr=PIPE)
# Sleep as long as requested and poll for results
sleep(timeout)
p.poll()
if p.returncode is None:
msg = timeout_msg + common_msg + "command:[{}]".format(command)
raise Exception(msg.format(timeout))
else:
if p.returncode != 0:
stdout, stderr = p.communicate()
msg = (
rc_non_zero_msg
+ common_msg
+ "command:[{}], return code:[{}], stdout:[{}], stderr:[{}] ".format(
command, p.returncode, stdout, stderr
)
)
raise Exception(msg)
return p.returncode
示例8: start
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import poll [as 别名]
def start(self):
"""Start the process."""
import shlex
from subprocess import Popen
if self.process:
raise RuntimeError("Process already started.")
if self.host and self.network_ping():
raise RuntimeError("A process is already running on port %s" %
self.port)
if isinstance(self.cmd, basestring):
cmd = shlex.split(self.cmd)
else:
cmd = self.cmd
self.null = open('/dev/null', 'w')
process = Popen(cmd, stdout=self.null, stderr=self.null, close_fds=True)
if not self.host:
time.sleep(0.35)
if process.poll():
output = process.communicate()[0]
raise RuntimeError("Did not start server! Woe!\n" + output)
self.process = process
return
start = time.time()
while process.poll() is None and time.time() - start < 15:
if self.network_ping():
break
else:
output = process.communicate()[0]
raise RuntimeError("Did not start server! Woe!\n" + output)
self.process = process
示例9: __init__
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import poll [as 别名]
class Inetd:
def __init__(self, inq, outq):
self.inq=inq
self.outq=outq
def start(self):
self.proc=Popen(['fossil', 'http', '/home/blanu/fossil/'], stdin=PIPE, stdout=PIPE)
# self.proc=Popen(['fossil', 'help'], stdin=PIPE, stdout=PIPE)
t=Thread(target=self.processIn)
t.setDaemon(True)
t.start()
t2=Thread(target=self.processOut)
# t2.setDaemon(True)
t2.start()
def processIn(self):
self.proc.poll()
while not self.proc.returncode:
data=self.inq.get()
print('inetd -> '+str(data))
self.proc.stdin.write(data)
self.proc.stdin.flush()
self.proc.poll()
def processOut(self):
print('waiting to finish')
# self.proc.wait()
print('finished')
print('waiting to read from inetd')
data=self.proc.stdout.read()
print('inetd <- '+str(data))
self.outq.put(data)
示例10: yes_proc
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import poll [as 别名]
def yes_proc(args, yes="yes"):
proc = Popen(args, stdin=PIPE)
while proc.returncode is None:
proc.communicate(yes)
proc.poll()
return proc.returncode == 0
示例11: wait_process_finish
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import poll [as 别名]
def wait_process_finish(scan, profile_fname):
'''
Start w3af process in new process, and wait while it terminate
'''
process = Popen([settings.W3AF_RUN,
'--no-update', '-P',
profile_fname],
stdout=PIPE,
stderr=PIPE)
scan.pid = process.pid
scan.save()
while process.returncode is None:
scan.last_updated = datetime.today()
scan.save()
sleep(W3AF_POLL_PERIOD) # wail
process.poll() # get process status
scan.set_task_status_free()
finish_time = datetime.now()
scan.finish = finish_time
scan.save()
target = scan.scan_task.target
target.last_scan = finish_time
target.save()
logger.info('w3af Process return code %s' % process.returncode)
return process.returncode
示例12: start
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import poll [as 别名]
def start(self, timeout = 20):
if self.is_running():
raise Exception('%s is already running' % self.name)
if not self.run_cmd:
raise Exception('No starting command registered for %s' % self.name)
if type(self.run_cmd) is types.FunctionType:
self.run_cmd()
return
with tempfile.TemporaryFile() as stdout_file, tempfile.TemporaryFile() as stderr_file:
proc = Popen(shlex.split('%s -p %s' % (self.run_cmd, self.port)), cwd = self.dir, close_fds = True,
stdout = stdout_file, stderr = stderr_file)
if timeout > 0:
poll_rate = 0.1
for i in range(int(timeout/poll_rate)):
if self.is_running():
break
sleep(poll_rate)
if bool(proc.poll()): # process ended with error
stdout_file.seek(0)
stderr_file.seek(0)
raise Exception('Run of %s ended unexpectfully: %s' % (self.name, [proc.returncode, stdout_file.read().decode(errors = 'replace'), stderr_file.read().decode(errors = 'replace')]))
elif proc.poll() == 0: # process runs other process, and ended
break
if self.is_running():
if self.check_connectivity():
return True
raise Exception('Daemon process is running, but no connectivity')
raise Exception('%s failed to run.' % self.name)
示例13: TestServer
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import poll [as 别名]
class TestServer(unittest.TestCase):
server = 'WSGIRefServer'
port = 12643
def setUp(self):
# Start servertest.py in a subprocess
cmd = [sys.executable, serverscript, self.server, str(self.port)]
cmd += sys.argv[1:] # pass cmdline arguments to subprocesses
self.p = Popen(cmd, stdout=PIPE, stderr=PIPE)
# Wait for the socket to accept connections
for i in xrange(100):
time.sleep(0.1)
# Check if the process has died for some reason
if self.p.poll() != None: break
if ping('127.0.0.1', self.port): break
def tearDown(self):
while self.p.poll() is None:
os.kill(self.p.pid, signal.SIGINT)
time.sleep(0.1)
if self.p.poll() is None:
os.kill(self.p.pid, signal.SIGTERM)
for stream in (self.p.stdout, self.p.stderr):
for line in stream:
if tob('Warning') in line \
or tob('Error') in line:
print line.strip().decode('utf8')
def fetch(self, url):
try:
return urllib2.urlopen('http://127.0.0.1:%d/%s' % (self.port, url)).read()
except Exception, e:
return repr(e)
示例14: __init__
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import poll [as 别名]
class Engine:
def __init__(self, cmdline):
self.proc = Popen(cmdline, stdin = PIPE, stdout = PIPE)
self.proc_com = _ProcCom(self.proc)
self.proc_com.start()
def send(self, msg):
self.proc.stdin.write(msg)
self.proc.stdin.flush()
def readline(self, timeout=None):
if self.proc.poll():
return ""
try:
msg = self.proc_com.outq.get(timeout=timeout)
except Empty:
raise socket.timeout()
return msg
def cleanup(self):
self.proc_com.stop.set()
if self.proc.poll() is None:
if sys.platform == 'win32':
import ctypes
handle = int(self.proc._handle)
ctypes.windll.kernel32.TerminateProcess(handle, 0)
else:
os.kill(self.proc.pid, signal.SIGTERM)
示例15: worker
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import poll [as 别名]
def worker(self, cmd_q, res_q):
while True:
name, cmd = cmd_q.get(True)
self.log.debug("External : launch %s" % cmd)
try:
proc = Popen(
cmd,
stdin=None, stdout=PIPE, stderr=STDOUT, close_fds=True)
output = ""
while True:
out, err = proc.communicate()
proc.poll()
output += out.decode('utf-8')
if proc.returncode is not None:
break
except:
self.log.debug(traceback.format_exc())
# Truncate multi-line output
try:
output = output[:output.index("\n")]
except:
pass
res_q.put_nowait(
(name, proc.returncode, output, int(time.time())))
cmd_q.task_done()