本文整理汇总了Python中subprocess.Popen.terminate方法的典型用法代码示例。如果您正苦于以下问题:Python Popen.terminate方法的具体用法?Python Popen.terminate怎么用?Python Popen.terminate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类subprocess.Popen
的用法示例。
在下文中一共展示了Popen.terminate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ProcessHostapd
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import terminate [as 别名]
class ProcessHostapd(QThread):
statusAP_connected = pyqtSignal(object)
def __init__(self,cmd):
QThread.__init__(self)
self.cmd = cmd
def run(self):
print 'Starting Thread:' + self.objectName()
self.makeLogger()
self.process = Popen(self.cmd,stdout=PIPE,stderr=STDOUT)
for line in iter(self.process.stdout.readline, b''):
#self.log_hostapd.info(line.rstrip())
if self.objectName() == 'hostapd':
if 'AP-STA-DISCONNECTED' in line.rstrip() or 'inactivity (timer DEAUTH/REMOVE)' in line.rstrip():
self.statusAP_connected.emit(line.split()[2])
def makeLogger(self):
setup_logger('hostapd', './Logs/AccessPoint/requestAP.log')
self.log_hostapd = logging.getLogger('hostapd')
def stop(self):
print 'Stop thread:' + self.objectName()
if self.process is not None:
self.process.terminate()
self.process = None
示例2: train
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import terminate [as 别名]
def train(self, corpus, time_slices, mode='fit', model='fixed'):
"""
Train DTM model using specified corpus and time slices.
'mode' controls the mode of the mode: 'fit' is for training, 'time' for
analyzing documents through time according to a DTM, basically a held out set.
'model' controls the coice of model. 'fixed' is for DIM and 'dtm' for DTM.
"""
self.convert_input(corpus, time_slices)
arguments = "--ntopics={p0} --model={mofrl} --mode={p1} --initialize_lda={p2} --corpus_prefix={p3} --outname={p4} --alpha={p5}".format(
p0=self.num_topics, mofrl=model, p1=mode, p2=self.initialize_lda, p3=self.fcorpus(), p4=self.foutname(), p5=self.alpha)
params = "--lda_max_em_iter={p0} --lda_sequence_min_iter={p1} --lda_sequence_max_iter={p2} --top_chain_var={p3} --rng_seed={p4} ".format(
p0=self.lda_max_em_iter, p1=self.lda_sequence_min_iter, p2=self.lda_sequence_max_iter, p3=self.top_chain_var, p4=self.rng_seed)
arguments = arguments + " " + params
logger.info("training DTM with args %s" % arguments)
try:
p = Popen([self.dtm_path] + arguments.split(), stdout=PIPE, stderr=PIPE)
p.communicate()
except KeyboardInterrupt:
p.terminate()
self.em_steps = np.loadtxt(self.fem_steps())
self.init_alpha = np.loadtxt(self.finit_alpha())
self.init_beta = np.loadtxt(self.finit_beta())
self.init_ss = np.loadtxt(self.flda_ss())
self.lhood_ = np.loadtxt(self.fout_liklihoods())
# document-topic proportions
self.gamma_ = np.loadtxt(self.fout_gamma())
# cast to correct shape, gamme[5,10] is the proprtion of the 10th topic
# in doc 5
self.gamma_.shape = (self.lencorpus, self.num_topics)
# normalize proportions
self.gamma_ /= self.gamma_.sum(axis=1)[:, np.newaxis]
self.lambda_ = np.zeros((self.num_topics, self.num_terms * len(self.time_slices)))
self.obs_ = np.zeros((self.num_topics, self.num_terms * len(self.time_slices)))
for t in range(self.num_topics):
topic = "%03d" % t
self.lambda_[t, :] = np.loadtxt(self.fout_prob().format(i=topic))
self.obs_[t, :] = np.loadtxt(self.fout_observations().format(i=topic))
# cast to correct shape, lambda[5,10,0] is the proportion of the 10th
# topic in doc 5 at time 0
self.lambda_.shape = (self.num_topics, self.num_terms, len(self.time_slices))
self.obs_.shape = (self.num_topics, self.num_terms, len(self.time_slices))
# extract document influence on topics for each time slice
# influences_time[0] , influences at time 0
if model == 'fixed':
for k, t in enumerate(self.time_slices):
stamp = "%03d" % k
influence = np.loadtxt(self.fout_influence().format(i=stamp))
influence.shape = (t, self.num_topics)
# influence[2,5] influence of document 2 on topic 5
self.influences_time.append(influence)
示例3: outputPrestress
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import terminate [as 别名]
def outputPrestress(self):
cleardir('.', FILEPAT)
if os.path.exists(ODBFILE):
os.remove(ODBFILE)
if os.path.exists(TARGETFILE):
os.remove(TARGETFILE)
self.optlogger.info('INPUT THE TEMPERATURE OF THE THREAD IS %s', self.currentTems)
self.optlogger.info('START COMPUTING THE PRESTRESS .....')
file_change(INPFILE, self._linenos, self.currentTems)
createOdb = Popen(self._command_inp, shell=True)
self.pause(400)
self.optlogger.info('TERMINATE PROGRESS: %s', createOdb.pid)
createOdb.terminate()
fetchOdb = Popen(self._command_odb, shell=True)
self.optlogger.info('FETCH PRESTRESS FROM DATABASE...')
sleep(5)
print('COMPLECATED!')
self.optlogger.info('TERMINATE PROGRESS: %s', fetchOdb.pid)
fetchOdb.terminate()
with open(TARGETFILE, 'r+') as f:
f_list = f.readlines()
target = f_list[self._targetno-1]
print(target)
pat = re.compile(r'\[(.*?)\]', re.S)
target_str = pat.search(target).groups()[0]
outPrestress = [float(item)
for item in target_str.split(', ')]
self.optlogger.info('THE OUTPUT OF MODEL IS %s', outPrestress)
return outPrestress
示例4: testLocal
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import terminate [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())
示例5: testBasic
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import terminate [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())
示例6: execute_sequence
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import terminate [as 别名]
def execute_sequence(self, sequence):
def purify_args(args):
for rm_arg in ['-h, --hardware', ]:
try:
args.remove(rm_arg)
except ValueError:
pass
for add_arg in ['--no-gui', '--server']:
args.append(add_arg)
return args
while True:
for command in sequence['sequence']:
args = split(command['command'])
cwd = join(realpath(dirname(__file__)), '..', command['dir'])
args[0] = join(cwd, args[0])
process = Popen(purify_args(args), cwd=cwd)
print "Starting "+str(args)
reason = self.wait(command['timeout'], command['interruptible'], process) # TODO interruptible raw_input in new_thread for 2.7, exec with timeout= for 3
print "End:", reason
if reason!='terminated':
process.terminate() # SIGTERM
process.send_signal(SIGINT)
process.wait() # should poll() and kill() if it does not close?
if not sequence['infinite']:
break
示例7: test_listen
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import terminate [as 别名]
def test_listen(self):
# Start the listen command with a socket.
listen_daemon = Popen(self.listen_args, stdout=PIPE, stderr=PIPE)
# Wait a short while for the socket to be created.
time.sleep(1)
# Send command to and receive response from the listen command.
# (Implicit string concatenation, no summing needed.)
get_cmd = (b'{ "id": "0", "verb": "get",'
b' "path": "/routes/route[addr=1.2.3.4]/port" }\n')
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.connect(SOCKET_PATH)
sock.sendall(get_cmd)
resp = str(sock.recv(200), ENC)
finally:
sock.close()
status = json.loads(resp)['status']
self.assertEqual(status, 'ok')
# Terminate the listen command.
listen_daemon.terminate()
ret_code = listen_daemon.wait()
if ret_code not in (0, -SIGTERM):
print('Error terminating daemon:', listen_daemon.args)
print('Exit code:', ret_code)
print('STDOUT\n', str(listen_daemon.stdout.read(), ENC))
print('STDERR\n', str(listen_daemon.stderr.read(), ENC))
listen_daemon.stdout.close()
listen_daemon.stderr.close()
os.unlink(SOCKET_PATH)
示例8: RunServer
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import terminate [as 别名]
class RunServer(object):
def __init__(self, instance_name, port):
self.instance_name = instance_name
self.port = port
self.lan_ip = get_lan_ip()
self.process = None
self.out = None
def start(self):
self.stop()
cmd = [sys.executable, 'manage_%s.py' % self.instance_name,
'runserver', '--noreload', '--traceback', '0.0.0.0:%d' % self.port]
self.process = Popen(cmd)
sleep(3.0)
if self.process.poll() is not None:
self.stop()
raise RunException(ugettext("Error to start!"))
self.open_url()
def open_url(self):
webbrowser.open_new("http://%(ip)s:%(port)d" %
{'ip': self.lan_ip, 'port': self.port})
def stop(self):
if self.is_running():
self.process.terminate()
self.process = None
self.out = None
def is_running(self):
return (self.process is not None) and (self.process.poll() is None)
示例9: AbstractSubprocessClass
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import terminate [as 别名]
class AbstractSubprocessClass(object):
"""
Simple abstract wrapper class for commands that need to be
called with Popen and communicate with them
"""
def __init__(self, runnable, encoding="utf-8"):
self._runnable = runnable
self._encoding = encoding
self._closed = True
def start(self):
# print self._runnable
# print self.options
self._process = Popen([self._runnable] + self.options, stdin=PIPE, stdout=PIPE, stderr=PIPE)
self._closed = False
def stop(self):
if not self._closed:
# HACK: communicate() sometimes blocks here
self._process.terminate()
self._closed = True
def __exit__(self, exc_type, exc_value, traceback):
if not self._closed:
self.stop()
def __del__(self):
if not self._closed:
self.stop()
示例10: CppSim
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import terminate [as 别名]
class CppSim(ProcessWorkerThread):
def handle_eval(self, record):
val = np.nan
# Continuously check for new outputs from the subprocess
self.process = Popen([path, array2str(record.params[0])],
stdout=PIPE, bufsize=1, universal_newlines=True)
for line in self.process.stdout:
try:
val = float(line.strip()) # Try to parse output
if val > 250.0: # Terminate if too large
self.process.terminate()
self.finish_success(record, 250.0)
return
except ValueError: # If the output is nonsense we terminate
logging.warning("Incorrect output")
self.process.terminate()
self.finish_cancelled(record)
return
self.process.wait()
rc = self.process.poll() # Check the return code
if rc < 0 or np.isnan(val):
logging.info("WARNING: Incorrect output or crashed evaluation")
self.finish_cancelled(record)
else:
self.finish_success(record, val)
示例11: collect_events
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import terminate [as 别名]
def collect_events(self):
on_posix = 'posix' in sys.builtin_module_names
# Helper function for quickly reading raw output.
def enqueue_output(out, queue):
for l in iter(out.readline, ''):
queue.put(l)
p = Popen(['adb', 'shell', 'getevent', '-lt'], stdout=PIPE, bufsize=1, close_fds=on_posix)
t = Thread(target=enqueue_output, args=(p.stdout, self.raw_data_queue))
t.daemon = True
t.start()
try:
# Process the events in this thread.
print 'Processing android events from device:'
self.previous_state = ui.device.dump()
while True:
try:
line = self.raw_data_queue.get_nowait().strip()
self.preprocess_line(line)
except Empty:
# Ignore empty events, we're simply reading too quickly.
pass
except KeyboardInterrupt:
print 'Finished processing events from device.'
p.terminate()
示例12: ProcessThread
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import terminate [as 别名]
class ProcessThread(threading.Thread):
def __init__(self,cmd):
threading.Thread.__init__(self)
self.cmd = cmd
self.process = None
self.logger = False
def run(self):
print 'Starting Thread:' + self.name
if self.name == 'Airbase-ng':
setup_logger('airbase', './Logs/requestAP.log')
log_airbase = logging.getLogger('airbase')
log_airbase.info('---[ Start Airbase-ng '+asctime()+']---')
log_airbase.info('-'*52)
self.logger = True
self.process = Popen(self.cmd,stdout=PIPE,stderr=STDOUT)
for line in iter(self.process.stdout.readline, b''):
if self.logger:
if not search(Refactor.getHwAddr(Refactor.get_interfaces()['activated']),
str(line.rstrip()).lower()):
log_airbase.info(line.rstrip())
print (line.rstrip())
def stop(self):
print 'Stop thread:' + self.name
if self.process is not None:
self.process.terminate()
self.process = None
示例13: OnWriteHandler
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import terminate [as 别名]
class OnWriteHandler(pyinotify.ProcessEvent):
def my_init(self):
self.start_serve()
self.last = None
def start_serve(self):
self.httpd = Popen(('python', '-m', 'SimpleHTTPServer', str(PORT)),
stdout=PIPE, cwd=SERVE)
print 'Serving at http://0.0.0.0:%i' % PORT
def stop_serve(self):
self.httpd.terminate()
self.httpd.wait()
self.httpd = None
print 'Server Terminated'
def recompile(self):
self.stop_serve()
compile.main(args)
self.start_serve()
def process_IN_MODIFY(self, event):
print event.maskname, event.name
name, ext = event.name.split('.')
if not (os.path.isfile(os.path.join(event.path, '%s.%s' % (name, 'soy')))
and ext == 'js'):
cur = '%s-%s' % (event.path, event.name)
if self.last == cur:
self.last = None
else:
self.last = cur
self.recompile()
示例14: ProcessThread
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import terminate [as 别名]
class ProcessThread(threading.Thread):
def __init__(self,cmd,):
threading.Thread.__init__(self)
self.cmd = cmd
self.iface = None
self.process = None
self.logger = False
self.prompt = True
def run(self):
print 'Starting Thread:' + self.name
if self.name == 'Dns2Proxy':
setup_logger('dns2proxy', './Logs/AccessPoint/dns2proxy.log')
log_dns2proxy = logging.getLogger('dns2proxy')
self.logger = True
self.process = Popen(self.cmd,stdout=PIPE,stderr=STDOUT)
for line in iter(self.process.stdout.readline, b''):
if self.logger:
if self.name == 'Dns2Proxy':
log_dns2proxy.info(line.rstrip())
self.prompt = False
if self.prompt:
print (line.rstrip())
def stop(self):
print 'Stop thread:' + self.name
if self.process is not None:
self.process.terminate()
self.process = None
示例15: test_command_send
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import terminate [as 别名]
def test_command_send(self):
# START SMTPD
tfile = tempfile.NamedTemporaryFile()
tfile_name = tfile.name
tfile.close()
p1 = Popen(['./tests/smtp_server.py', tfile_name], stdin=PIPE)
citems = self.get_testserver_config_scheme()
proj_dir = self.mm_create_project('Test')
config = SafeConfigParser()
config.read(self.config_path)
for item in citems:
config.set('Mail', item[0], item[1])
files = ['mail.txt', 'subject.txt', 'keys.csv', 'attachments.txt']
self.create_with_sample_files("", proj_dir, files)
config.write(open(self.config_path, 'w'))
sys.stdin = x_in = StringIO('\n')
sys.stdout = x_out = StringIO()
m = MMailer()
m.command_send(args=['mmailer', 'send'])
sys.stdin = sys.__stdin__
sys.stdout = sys.__stdout__
p1.terminate()
p1.wait()
of = open('tests/samples/send_output.txt','r')
sto_str = of.read()
sto = sto_str.decode('UTF-8')
# exclude first line from compare,
# because the date changes each test run
assert x_out.getvalue() == sto,"\n\n[%s]\n\n[%s]" \
% (sto, x_out.getvalue())
import filecmp
assert filecmp.cmp(tfile_name, 'tests/samples/sended.txt')