本文整理汇总了Python中subprocess.Popen.kill方法的典型用法代码示例。如果您正苦于以下问题:Python Popen.kill方法的具体用法?Python Popen.kill怎么用?Python Popen.kill使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类subprocess.Popen
的用法示例。
在下文中一共展示了Popen.kill方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: AirpnpProcess
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import kill [as 别名]
class AirpnpProcess(object):
def __init__(self, config={}):
self.config = config
def create_config(self, config):
f = tempfile.NamedTemporaryFile(delete=True)
f.write("[airpnp]\n")
for k, v in config.items():
f.write("%s=%s\n" % (k, v))
f.flush()
return f.name
def __enter__(self):
configfn = self.create_config(self.config)
args = ["twistd", "-n", "airpnp", "-c", configfn]
cwd = os.path.join(os.path.dirname(__file__), "..")
self.proc = Popen(args, stdout=PIPE, stderr=STDOUT, cwd=cwd, close_fds=ON_POSIX, bufsize=1)
q = Queue()
t = Thread(target=enqueue_output, args=(self.proc.stdout, q))
t.daemon = True
t.start()
return q
def __exit__(self, type, value, tb):
self.proc.kill()
示例2: process
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import kill [as 别名]
def process(self, request, response, report):
if response.is_html:
referrer = str(request)
pth = os.path.dirname(os.path.realpath(__file__))
proc = Popen([self.phantomJsPath, '{0}{1}scrape.js'.format(pth, os.sep), referrer], stdin=PIPE, stdout=PIPE, stderr=PIPE)
try:
out, err = proc.communicate(response.content.encode(), timeout=10)
rc = proc.returncode
except TimeoutExpired:
proc.kill()
out, err = proc.communicate()
if len(err) > 0:
report.add_error(err.decode('utf-8'))
else:
report.add_error(out.decode('utf-8'))
else:
if rc == 0:
result = out.decode('utf-8').strip()
urls = set()
for url in set(result.splitlines()):
if self._log_url(url):
urls.add(url)
self._add_request(url, referrer)
self._report(report, urls)
else:
if len(err) > 0:
report.add_error(err.decode('utf-8'))
else:
report.add_error(out.decode('utf-8'))
示例3: OpenPostgreSQLsshTunnel
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import kill [as 别名]
class OpenPostgreSQLsshTunnel(object):
""" Class to let us open an ssh tunnel, then close it when done """
def __init__(self, port=5432):
self.tunnel_process = 0
self.postgre_port = 5432
self.remote_port = port
def __enter__(self):
if HOSTNAME != 'dilepton-tower':
import time
import shlex
self.postgre_port = self.remote_port
_cmd = 'ssh -N -L localhost:%d' % self.remote_port + \
':localhost:5432 [email protected]'
args = shlex.split(_cmd)
self.tunnel_process = Popen(args, shell=False)
time.sleep(5)
return self.postgre_port
def __exit__(self, exc_type, exc_value, traceback):
if self.tunnel_process:
self.tunnel_process.kill()
if exc_type or exc_value or traceback:
return False
else:
return True
示例4: load_shell
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import kill [as 别名]
def load_shell(self, chunk):
"""Run shell commands from code chunks"""
if chunk['evaluate']:
lines = chunk['content'].lstrip().splitlines()
result = "\n"
for line in lines:
command = line.split()
major, minor = sys.version_info[:2]
cmd = Popen(command, stdout=PIPE)
if major == 2 or minor < 3: # Python 2 doesn't have timeout for subprocess
try:
content = cmd.communicate()[0].decode('utf-8').replace("\r", "") + "\n"
except Exception as e:
content = "Pweave ERROR can't execute shell command:\n %s\n" % command
content += str(e)
sys.stdout.write(" Pweave ERROR can't execute shell command:\n %s\n" % line)
print(str(e))
else:
try:
content = cmd.communicate(timeout=20)[0].decode('utf-8').replace("\r", "") + "\n"
except TimeoutExpired:
cmd.kill()
content, errs = cmd.communicate()
sys.stdout.write("Shell command timeout:\n %s\n" % line)
content = content.decode('utf-8').replace("\r", "") + "\n"
if chunk['term']:
result += "$ %s\n" % line
result += content
else:
result = ""
return result
示例5: __init__
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import kill [as 别名]
class Player:
def __init__(self, name, cmd):
self.name = name
self.forts = set()
self.marches = set()
args = cmd.split(' ')
self.process = Popen(list(args) + [name], stdin=PIPE, stdout=PIPE,
universal_newlines=True)
def capture(self, fort):
if fort.owner:
fort.owner.forts.remove(fort)
self.forts.add(fort)
fort.owner = self
def is_defeated(self):
return (not self.forts) and (not self.marches)
def send_state(self):
if not self.process.poll():
self.process.stdin.write(show_visible(self.forts))
self.process.stdin.write('\n')
self.process.stdin.flush()
def read_commands(self, game):
if not self.process.poll():
try:
read_commands(game, self, self.process.stdout)
except StopIteration:
self.process.kill()
示例6: MockServer
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import kill [as 别名]
class MockServer(object):
def __init__(self, http_port=None, https_port=None, proxy_port=None):
self.http_port = http_port if http_port is not None else get_ephemeral_port()
self.https_port = https_port if https_port is not None else get_ephemeral_port()
self.proxy_port = proxy_port if proxy_port is not None else get_ephemeral_port()
def __enter__(self):
self.proc = Popen([
sys.executable,
'-u', '-m', 'splash.tests.mockserver',
'--http-port', str(self.http_port),
'--https-port', str(self.https_port),
'--proxy-port', str(self.proxy_port),
],
env=get_testenv()
)
for port in (self.http_port, self.https_port, self.proxy_port):
_wait_for_port(port)
return self
def __exit__(self, exc_type, exc_value, traceback):
self.proc.kill()
self.proc.wait()
def url(self, path, gzip=True, host='localhost'):
gzip_path = '' if not gzip else '/gzip'
return "http://%s:%s%s/%s" % (
host, self.http_port, gzip_path, path.lstrip('/')
)
def https_url(self, path):
return "https://localhost:%s/%s" % (self.https_port, path.lstrip('/'))
示例7: err_check
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import kill [as 别名]
def err_check(alpha,coord_vector,slope,space_type): #Runs OPIUM, checks test config errors and returns their sum
if space_type == 'coeff':
test_vector = coord_vector.copy()
test_vector = test_vector - alpha*slope
grid = fit_to_func(test_vector,'fourier_cos')
setKB(grid)
elif space_type == 'valley':
test_vector = VtoC(coord_vector - alpha*slope)
grid = fit_to_func(test_vector,'fourier_cos')
setKB(grid)
else:
raise ValueError('space_type must be "coeff" or "valley"')
#Use threading to cancel OPIUM if it takes too long
proc = Popen('./opium ' + filename + ' ' + filename + '.log all rpt', shell=True)
proc_thread = threading.Thread(target=proc.communicate)
proc_thread.start()
proc_thread.join(timeout_sec)
if proc_thread.is_alive():
# Process still running - kill it and raise timeout error
try:
proc.kill()
except OSError, e:
# The process finished between the `is_alive()` and `kill()`
return proc.returncode
示例8: execute_test
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import kill [as 别名]
def execute_test():
retvalue = -1
envvars = os.environ.copy()
if platform.system() == "Linux":
libdir = envvars.get("CMAKE_LIBRARY_DIRECTORIES")
if libdir != None:
envvars["LD_LIBRARY_PATH"] = envvars["NDDSHOME"] + "/lib/" + example + ":" + libdir.replace(";", ":")
else:
envvars["LD_LIBRARY_PATH"] = envvars["NDDSHOME"] + "/lib/" + example + ":" + project_source_dir + "/lib"
# Run server
server = Popen([output_dir + "/bin/" + example + "/" + test_name + "ServerExample"], env=envvars)
# Wait 5 seconds before run client
sleep(5)
client = Popen([output_dir + "/bin/" + example + "/" + test_name + "ClientExample"], env=envvars)
client.wait()
client.communicate()
retvalue = client.returncode
server.kill()
return retvalue
示例9: getDeviceState
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import kill [as 别名]
def getDeviceState():
global deviceStatus
cmd = "adb devices"
devices = []
p = Popen(cmd,stdout=PIPE,shell=True)
for info in p.stdout.readlines():
info = info.decode()
if 'List' in info:
continue
elif 'offline' in info or 'unauthorized' in info or 'device' in info:
device = {}
name,state = [n.strip() for n in info.split('\t') if n.strip()]
device["deviceName"] = name
device["state"] = state
if ":" in name:
device["replacedName"] = name.replace(".","").replace(":","")
else:
device["replacedName"] = name
devices.append(device)
if name not in deviceStatus.keys():
deviceStatus[name] = False
else:
continue
p.kill()
return devices
示例10: launch_spl
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import kill [as 别名]
def launch_spl(self):
need_launch_in_shell = (os.name == "nt")
# launch sploit proccess with team_ip as arg
spl = Popen([self.sploit_name, self.team_ip],
stdout=PIPE, stderr=STDOUT, bufsize=1,
shell=need_launch_in_shell)
q = Queue()
# we are processing output in other thread to prevent blocking
def enqueue_output(queue, out):
while True:
line = out.readline()
queue.put(line)
if not line:
break
t = Thread(target=enqueue_output, args=(q, spl.stdout))
t.daemon = True
t.start()
# get output by lines until EOF
while True:
try:
remaining_time = MAX_RUNTIME - (time() - self.last_launch_time)
line = q.get(timeout=remaining_time)
except (Empty, ValueError):
log("Killing %s sploit(tried to run for more than %d secs)" % (
self.team_name, MAX_RUNTIME))
break
if not line:
break
line = line.strip()
if not line:
continue
if self.cycle_num == 1:
print("%s: %s" % (self.team_name, line))
flags = re.findall(FLAG_FORMAT, line)
OWNER_LOCK.acquire()
for flag in flags:
if flag not in self.flags:
if self.cycle_num == 1:
log("Flag from %s: %s" % (self.team_name, flag))
with open(self.flag_filename, "ab", 0) as f:
f.write(flag + b"\n")
self.flags.add(flag)
else:
if self.cycle_num == 1:
log("Flag from %s: %s (dup)" % (self.team_name, flag))
OWNER_LOCK.release()
if os.name != "nt":
spl.kill()
else:
spl.communicate()
示例11: tesseract_ocr_and_render_pdf
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import kill [as 别名]
def tesseract_ocr_and_render_pdf(
input_files,
output_file,
log,
pdfinfo,
pdfinfo_lock):
input_image = next((ii for ii in input_files if ii.endswith('.png')), '')
input_pdf = next((ii for ii in input_files if ii.endswith('.pdf')))
if not input_image:
# Skipping this page
re_symlink(input_pdf, output_file)
return
args_tesseract = [
'tesseract',
'-l', '+'.join(options.language),
input_image,
os.path.splitext(output_file)[0], # Tesseract appends suffix
'pdf'
] + options.tesseract_config
p = Popen(args_tesseract, close_fds=True, stdout=PIPE, stderr=PIPE,
universal_newlines=True)
try:
stdout, stderr = p.communicate(timeout=options.tesseract_timeout)
if stdout:
log.info(stdout)
if stderr:
log.error(stderr)
except TimeoutExpired:
p.kill()
log.info("Tesseract - page timed out")
re_symlink(input_pdf, output_file)
示例12: getLines
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import kill [as 别名]
def getLines(self):
lines = [str(line) for line in vim.current.buffer]
(row, col) = vim.current.window.cursor
cur_line = lines[row-1]
cur_line = cur_line[:col] + self.base + "AUTO332" + cur_line[col:]
lines[row-1] = cur_line
input_buffer = "\n".join(lines)
# Send the buffer to hh_client and return the lines
args = [
Const.CLIENT,
r'--auto-complete'
]
proc = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
proc.stdin.write(input_buffer);
out = proc.communicate()[0]
base = self.base
try:
proc.kill();
except:
pass
proc = args = None
#Util.debugf('getLines.txt', locals())
return [x for x in out.split("\n") if len(x) > 0]
示例13: wpa_run
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import kill [as 别名]
def wpa_run(self):
dump_cmd = ['airodump-ng', '-c', self.channel, '--bssid', self.bssid, '-w', './log/' + self.bssid, self.iface]
airodump_proc = Popen(dump_cmd, stdout=DN, stderr=DN)
self.proc_list.append(airodump_proc)
self.send_deauths()
while self.key == '':
output = Popen('tshark -r ./log/' + self.bssid + '-01.cap 2>/dev/null| grep "Message 4 of 4"',shell=True, stdout=PIPE).communicate()[0]
if output.find('Message 4 of 4') != -1:
execute('rm ./log/'+self.bssid+'.key')
airodump_proc.kill()
airodump_proc.communicate()
crack_cmd = ['aircrack-ng', '-w', self.password_list, '-b', self.bssid, './log/' + self.bssid + '-01.cap','-l', './log/' + self.bssid + '.key']
crack_proc = Popen(crack_cmd, stdout=DN)
self.proc_list.append(crack_proc)
crack_proc.wait()
try:
f = open('./log/' + self.bssid + '.key')
key = f.read()
f.close()
self.key = key
self.crack_success = True
self.stop()
except:
pass
else:
self.send_deauths()
time.sleep(5)
return self.key
示例14: __init__
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import kill [as 别名]
class DisqueNode:
def __init__(self, port, dir):
self.port = port
self.dir = dir
self.proc = None
self.socket = os.path.join(dir, 'disque.sock')
def start(self):
if not self.proc:
cmd = ["disque-server",
"--port", str(self.port),
"--dir", self.dir,
"--unixsocket", self.socket,
"--unixsocketperm", "755"]
self.proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
cmd = ['disque', '-p', str(self.port), 'info']
while True:
sleep(.01)
if self.proc.poll():
raise Exception('already stopped!', self.proc.stderr)
resp = run(cmd, stdout=PIPE, stderr=PIPE)
if not resp.returncode:
break
def stop(self):
self.proc.kill()
self.proc = None
@property
def configuration(self):
return Configuration(port=self.port, dir=self.dir, socket=self.socket)
示例15: has_active_torrents
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import kill [as 别名]
def has_active_torrents():
""" Check for any active torrents on the local deluged server.
:return: True if one or more torrents are active
:rtype: Bool
"""
std_output, std_err_output = '', ''
proc = None
try:
proc = Popen(["deluge-console", "info"], stdout=PIPE, stderr=PIPE)
std_output, std_err_output = proc.communicate()
# Decode
std_output = std_output.decode("utf-8")
std_err_output = std_err_output.decode("utf-8")
except (OSError, ValueError):
if proc is not None:
proc.kill()
raise RuntimeError("deluge-console could not be found, " +
"make sure it is installed")
if ('fatal' in std_output) or (
'fatal' in std_err_output) or proc.returncode >= 1:
raise RuntimeError("Status check failed, " +
"make sure that deluged is running")
else:
# Success!
return std_output.strip() != ""