本文整理汇总了Python中subprocess.Popen.send_signal方法的典型用法代码示例。如果您正苦于以下问题:Python Popen.send_signal方法的具体用法?Python Popen.send_signal怎么用?Python Popen.send_signal使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类subprocess.Popen
的用法示例。
在下文中一共展示了Popen.send_signal方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_tests
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import send_signal [as 别名]
def run_tests(tmpdir):
socket_file = os.path.join(tmpdir, "logductd.sock")
logs_dir = os.path.join(tmpdir, "logs")
daemon = Popen([sys.executable, "-m", "logduct.daemon", "-s", socket_file, "-d", logs_dir, "--trust-blindly"])
unit = "dummyunit"
stdio_log = os.path.join(logs_dir, unit, "stdio.log")
third_log = os.path.join(logs_dir, unit, "third.log")
try:
wait_until_exists(socket_file)
# stdio
check_call([sys.executable, "-m", "logduct.run", "-s", socket_file, "-u", unit, "echo", "hello"])
wait_until_exists(stdio_log)
data = slurp(stdio_log)
match = re.match(r"\d\d:\d\d:\d\d.\d\d\d (unknown|echo)\[\d+\]: hello\n", data)
assert match
# pipe fd
check_call([sys.executable, "-m", "logduct.run", "-s", socket_file, "-u", unit, "--fd", "3:third",
"--no-stdio", "bash", "-c", "echo there >&3"])
wait_until_exists(third_log)
data = slurp(third_log)
match = re.match(r"\d\d:\d\d:\d\d.\d\d\d: there\n", data)
assert match
finally:
daemon.send_signal(signal.SIGTERM)
time.sleep(0.2)
daemon.kill()
示例2: start_stop
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import send_signal [as 别名]
def start_stop(num:int,
interval:int,
pause:float=0.1,
vms=None):
import shlex
""" Like freezing, but do not make any. """
for vm in vms:
if vm.bname == 'sdag':
break
PERF = "/home/sources/perf_lite"
CMD = "{perf} kvm stat -e instructions,cycles -o {out} -x, -I {subinterval} -p {pid}"
out = "results/limit/start_stop_f_subint1_%s.csv" % vm.bname
cmd = CMD.format(perf=PERF, pid=vm.pid, out=out, subinterval=1)
p = Popen(shlex.split(cmd))
for i in range(1, num+1):
#print("%s out of %s" % (i, num))
if pause:
sleep(pause)
vm.exclusive()
sleep(interval/1000)
vm.shared()
print("done")
p.send_signal(2) # SIGINT
return None
示例3: vpn_manager
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import send_signal [as 别名]
def vpn_manager(ovpn):
""" Check VPN season
If vpn tunnel break or fail to create, terminate vpn season
So openvpn not keep sending requests to proxy server and
save you from being blocked.
"""
global dns, verbose, dropped_time
command = ['openvpn', '--config', ovpn]
p = Popen(command, stdout=PIPE, stdin=PIPE)
try:
while p.poll() is None:
line = p.stdout.readline()
if verbose == 'yes':
print line,
if 'Initialization Sequence Completed' in line:
dropped_time = 0
dns_manager('change', dns)
print ctext('VPN tunnel established successfully'.center(40), 'B')
print 'Ctrl+C to quit VPN'.center(40)
elif 'Restart pause, ' in line and dropped_time <= max_retry:
dropped_time += 1
print ctext('Vpn has restarted %s time' % dropped_time, 'rB')
elif dropped_time == max_retry or 'Connection timed out' in line or 'Cannot resolve' in line:
dropped_time = 0
print line
print ctext('Terminate vpn', 'B')
p.send_signal(signal.SIGINT)
except KeyboardInterrupt:
p.send_signal(signal.SIGINT)
p.wait()
print ctext('VPN tunnel is terminated'.center(40), 'B')
finally:
dns_manager('restore')
示例4: run
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import send_signal [as 别名]
def run(self):
try:
if osflag:
proc=Popen(self.cmd,shell=False,stdin=None,stdout=PIPE,\
stderr=STDOUT,bufsize=0)
else:
from subprocess import STARTUPINFO
si=STARTUPINFO()
si.dwFlags|=1
si.wShowWindow=0
proc=Popen(self.cmd,shell=False,stdin=None,stdout=PIPE,\
stderr=STDOUT,bufsize=0,startupinfo=si)
while 1:
if self.stop_flag:
if osflag: proc.send_signal(signal.SIGKILL)
else: proc.kill()
break
if osflag:
if proc.stdout in select.select([proc.stdout],[],[],1)[0]:
line=proc.stdout.readline()
else: line=' \n'
else: line=proc.stdout.readline()
if not len(line): break
else:
if count(line,'ttl') or count(line,'TTL'): self.retries=0
else: self.retries=self.retries+1
line=' '
sleep(0.5)
proc.poll()
except: pass
示例5: __init__
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import send_signal [as 别名]
class Process:
def __init__(self, args, name=None, keep_alive=False):
self.args = args
self.proc = None
self.name = name
self.keep_alive = keep_alive
if self.name is None:
self.name = "%s" % self.args
def start(self):
if not self.running():
rospy.loginfo("Starting process %s" % self.name)
self.proc = Popen(self.args)
else:
rospy.loginfo("Process %s already started" % self.name)
def stop(self):
if self.proc is not None:
if self.running():
rospy.loginfo("Stopping process %s" % self.name)
self.proc.send_signal(signal.SIGINT)
self.proc.wait()
else:
rospy.loginfo("Process %s already stopped" % self.name)
def restart(self):
rospy.loginfo("Restarting process %s" % self.name)
self.stop()
time.sleep(1) #TODO
self.start()
def running(self):
started = self.proc is not None
running = started and self.proc.poll() is None
return running
示例6: execute_sequence
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import send_signal [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_shell_background_support_setsid
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import send_signal [as 别名]
def test_shell_background_support_setsid(both_debug_modes, setsid_enabled):
"""In setsid mode, dumb-init should suspend itself and its children when it
receives SIGTSTP, SIGTTOU, or SIGTTIN.
"""
proc = Popen(
('dumb-init', sys.executable, '-m', 'tests.lib.print_signals'),
stdout=PIPE,
)
match = re.match(b'^ready \(pid: ([0-9]+)\)\n$', proc.stdout.readline())
pid = match.group(1).decode('ascii')
for signum in SUSPEND_SIGNALS:
# both dumb-init and print_signals should be running or sleeping
assert process_state(pid) in ['running', 'sleeping']
assert process_state(proc.pid) in ['running', 'sleeping']
# both should now suspend
proc.send_signal(signum)
os.waitpid(proc.pid, os.WUNTRACED)
assert process_state(proc.pid) == 'stopped'
assert process_state(pid) == 'stopped'
# and then both wake up again
proc.send_signal(SIGCONT)
assert (
proc.stdout.readline() == '{0}\n'.format(SIGCONT).encode('ascii')
)
assert process_state(pid) in ['running', 'sleeping']
assert process_state(proc.pid) in ['running', 'sleeping']
for pid in pid_tree(proc.pid):
os.kill(pid, SIGKILL)
示例8: test_shell_background_support_without_setsid
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import send_signal [as 别名]
def test_shell_background_support_without_setsid(both_debug_modes, setsid_disabled):
"""In non-setsid mode, dumb-init should forward the signals SIGTSTP,
SIGTTOU, and SIGTTIN, and then suspend itself.
"""
proc = Popen(
('dumb-init', sys.executable, '-m', 'tests.lib.print_signals'),
stdout=PIPE,
)
assert re.match(b'^ready \(pid: (?:[0-9]+)\)\n$', proc.stdout.readline())
for signum in SUSPEND_SIGNALS:
assert process_state(proc.pid) in ['running', 'sleeping']
proc.send_signal(signum)
assert proc.stdout.readline() == '{0}\n'.format(signum).encode('ascii')
os.waitpid(proc.pid, os.WUNTRACED)
assert process_state(proc.pid) == 'stopped'
proc.send_signal(SIGCONT)
assert (
proc.stdout.readline() == '{0}\n'.format(SIGCONT).encode('ascii')
)
assert process_state(proc.pid) in ['running', 'sleeping']
for pid in pid_tree(proc.pid):
os.kill(pid, SIGKILL)
示例9: sh
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import send_signal [as 别名]
def sh(cd, f):
simLog(f, 'CMD: ' + ' '.join(cd))
simLog(f, 'DIR: ' + HTML + 'upload/')
sub = Popen(cd, cwd = HTML + 'upload/', stdout = PIPE, stderr = PIPE, stdin = PIPE, close_fds=True, preexec_fn = os.setsid)
try:
print 'Sub Id: ', sub.pid
# while sub.poll() is None:
while True:
sub.stdout.flush()
tstr = sub.stdout.readline()
if sub.poll() is not None and not tstr:
break
simLog(f, tstr.strip('\n'))
f.flush()
time.sleep(0.1)
retcode = sub.poll()
simLog(f, 'Poll: ' + str(retcode))
retcode = sub.wait()
simLog(f, 'Wait: ' + str(retcode))
f.flush()
except KeyboardInterrupt:
sub.send_signal(signal.SIGTERM)
sub.terminate()
sub.kill()
os.killpg(sub.pid,signal.SIGTERM)
sub.wait()
print 'Kill Sub'
except Exception, ex:
print ex
示例10: __init__
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import send_signal [as 别名]
class GHCI:
def __init__(self):
self.process = Popen(["ghci", "-v0", "+RTS -M1k"], stdout=PIPE, stdin=PIPE, stderr=PIPE)
self.stdin = self.process.stdin
self.stdout = self.process.stdout
self.stderr = self.process.stderr
self.devnull = open(devnull, "w")
fcntl(self.stdout.fileno(), F_SETFL, O_NONBLOCK)
fcntl(self.stderr.fileno(), F_SETFL, O_NONBLOCK)
def __del__(self):
self.process.kill()
def execute(self, code):
self.stdin.flush()
self.stdout.flush()
self.stderr.flush()
self.stdout.read()
self.stderr.read()
self.stdin.write(bytes(code + "\n", "utf-8"))
self.stdin.flush()
self.stdout.flush()
self.stderr.flush()
def evaluate(self, code):
self.stdin.flush()
self.stdout.flush()
self.stderr.flush()
self.stdout.read()
self.stderr.read()
self.stdin.write(bytes(code + "\n", "utf-8"))
self.stdin.flush()
self.stdout.flush()
self.stderr.flush()
# read input
out = ""
fds = select([self.stdout, self.stderr], [], [], 5)[0]
if len(fds) > 0:
for fd in fds:
fd.flush()
line = fd.readline().decode("utf-8")
out += line
print(out.strip(), end="", flush=True)
return True
else:
self.process.send_signal(SIGINT)
return False
def close(self):
self.stdin.close()
self.stdout.close()
self.stderr.close()
示例11: pd
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import send_signal [as 别名]
class pd(object):
@staticmethod
def _getPdBin(pdbin):
if pdbin is None:
if "PD_BIN" in os.environ:
return os.environ["PD_BIN"]
else:
if sys.platform == "win32":
return os.path.join("pd", "bin", "pd.exe")
elif sys.platform == "linux2":
return "pd"
elif sys.platform == "darwin":
return os.path.join("", "Applications", "Pd.app",
"Contents", "Resources", "bin", "pd")
else:
raise PdException("Unknown Pd executable location on your"
" platform ({}).".format(sys.platform))
else:
return pdbin
def __init__(self, stderr=True, nogui=True, initPatch=None, bin=None):
self.pdbin = pd._getPdBin(bin)
args = [self.pdbin]
self.pdsend = os.path.join(os.path.dirname(self.pdbin), "pdsend")
self.port = DEFAULT_PORT
if stderr:
args.append("-stderr")
if nogui:
args.append("-nogui")
if initPatch:
args.append("-open")
args.append(initPatch)
try:
print(args)
self.proc = Popen(args, stdin=None, stderr=PIPE, stdout=PIPE,
close_fds=(sys.platform != "win32"))
except OSError:
raise PdException(
"Problem running `{}` from '{}'".format(self.pdbin,
os.getcwd()))
def send(self, msg):
args = [self.pdsend, str(DEFAULT_PORT)]
print(args, msg)
msg = "; " + msg + ";"
sendProc = Popen(args, stdin=PIPE, close_fds=(sys.platform != "win32"),
universal_newlines=True)
out, err = sendProc.communicate(input=msg)
def kill(self):
self.proc.send_signal(signal.SIGINT)
if self.proc:
self.proc.wait()
示例12: _close_app_process
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import send_signal [as 别名]
def _close_app_process(process: subprocess.Popen):
# SIGINT instead of terminate,
# so that subprocess coverage works without special signal handling
process.send_signal(signal.SIGINT)
try:
process.wait(3)
except subprocess.TimeoutExpired:
process.kill()
pytest.fail("The process didn't close on time.")
示例13: test_bridgedb_commands
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import send_signal [as 别名]
def test_bridgedb_commands(self):
print('')
here = os.getcwd()
runDir = pjoin(here, 'rundir')
topDir = here.rstrip('_trial_temp')
scriptsDir = pjoin(topDir, 'scripts')
# Create the lowest directory we need, and all its parents:
os.makedirs(os.path.join(runDir, 'gnupghome'))
conf = pjoin(topDir, 'bridgedb.conf')
confMoved = pjoin(runDir, 'bridgedb.conf')
gpgFile = pjoin(topDir, 'gnupghome', 'TESTING.subkeys.sec')
gpgMoved = pjoin(runDir, 'gnupghome', 'TESTING.subkeys.sec')
certFile = pjoin(topDir, 'cert')
certMoved = pjoin(runDir, 'cert')
keyFile = pjoin(topDir, 'privkey.pem')
keyMoved = pjoin(runDir, 'privkey.pem')
makeSSLCertScript = os.path.join(scriptsDir, 'make-ssl-cert')
bridgedbScript = which('bridgedb') # this returns a list
self.doCopyFile(conf, confMoved, 'config')
self.doCopyFile(gpgFile, gpgMoved, 'GPG test key')
print("Running subcommands from directory:\n %r" % runDir)
print("Running %r..." % makeSSLCertScript)
makeSSLCertProcess = Popen(makeSSLCertScript)
makeSSLCertProcess.wait()
self.doMoveFile(certFile, certMoved, 'certificate')
self.doMoveFile(keyFile, keyMoved, 'SSL private key')
self.assertTrue(os.path.isfile(bridgedbScript[0]),
"Couldn't find bridgedb script %r" % bridgedbScript[0])
bridgedbScript = bridgedbScript[0]
print("Running bridgedb script %r..." % bridgedbScript)
os.chdir(runDir) # we have to do this to get files to end up there
print("Running `bridgedb mock' to generate mock bridge descriptors...")
mockProc = Popen([bridgedbScript, 'mock', '-n', '50'])
mockProcCode = mockProc.wait()
print("`bridgedb mock' exited with status code %d" % int(mockProcCode))
os.chdir(here)
# See ticket #11216, cached-extrainfo* files should not be parsed
# cumulatively.
eidesc = pjoin(runDir, 'cached-extrainfo')
eindesc = pjoin(runDir, 'cached-extrainfo.new')
self.doCopyFile(eindesc, eidesc, 'duplicated cached-extrainfo(.new)')
print("Running `bridgedb' to test server startups...")
bridgedbProc = Popen([bridgedbScript, '-r', runDir])
time.sleep(30)
bridgedbProc.send_signal(signal.SIGINT)
bridgedbProcCode = bridgedbProc.wait()
print("`bridgedb' exited with status code %d" % int(bridgedbProcCode))
self.assertEqual(bridgedbProcCode, 0)
示例14: handle
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import send_signal [as 别名]
def handle(self, *args, **options):
shutdown_message = options.get('shutdown_message', '')
application = options.get('application')
version = options.get('version')
from djangae.boot import setup_paths, find_project_root
setup_paths()
project_root = find_project_root()
expected_path = os.path.join(project_root, "app.yaml")
if not os.path.exists(expected_path):
sys.stderr.write("Unable to find app.yaml at '%s'\n" % expected_path)
sys.exit(1)
# Will have been set by setup_paths
sdk_path = os.environ['APP_ENGINE_SDK']
appcfg = os.path.join(sdk_path, "appcfg.py")
# very simple for now, only runs appcfg.py update . and some
# extra parameters like app id or version
command = [
appcfg,
"update",
project_root
]
if application:
command += ["-A", application]
if version:
command += ["-V", version]
process = Popen(
command,
stdout=sys.__stdout__,
stderr=sys.__stderr__,
cwd=project_root
)
try:
process.wait()
except KeyboardInterrupt:
#Tell the dev appserver to shutdown and forcibly kill
#if it takes too long
process.send_signal(signal.SIGTERM)
time.sleep(2)
process.kill()
if shutdown_message:
sys.stdout.write(shutdown_message)
sys.exit(process.returncode)
示例15: SplashServer
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import send_signal [as 别名]
class SplashServer(object):
def __init__(self, logfile=None, proxy_profiles_path=None,
js_profiles_path=None, filters_path=None, portnum=None,
proxy_portnum=None, extra_args=None, verbosity=3):
self.logfile = logfile
self.proxy_profiles_path = proxy_profiles_path
self.js_profiles_path = js_profiles_path
self.filters_path = filters_path
self.verbosity = verbosity
self.portnum = portnum if portnum is not None else get_ephemeral_port()
self.proxy_portnum = proxy_portnum if proxy_portnum is not None else get_ephemeral_port()
self.tempdir = tempfile.mkdtemp()
self.extra_args = extra_args or []
def __enter__(self):
args = [sys.executable, '-u', '-m', 'splash.server']
args += ['--cache-path', self.tempdir]
args += ['--port', str(self.portnum)]
args += ['--verbosity', str(self.verbosity)]
if self.logfile:
args += ['-f', self.logfile]
if self.proxy_profiles_path:
args += ['--proxy-profiles-path', self.proxy_profiles_path]
if self.js_profiles_path:
args += ['--js-profiles-path', self.js_profiles_path]
if self.filters_path:
args += ['--filters-path', self.filters_path]
if self.proxy_portnum:
args += ['--proxy-portnum', str(self.proxy_portnum)]
args.extend(self.extra_args)
self.proc = Popen(args, env=get_testenv())
self.proc.poll()
if self.proc.returncode is not None:
msg = ("unable to start splash server. return code: %d" %
self.proc.returncode)
raise RuntimeError(msg)
_wait_for_port(self.portnum)
return self
def __exit__(self, exc_type, exc_value, traceback):
if self.proc is not None:
self.proc.send_signal(signal.SIGINT)
self.proc.wait()
self.proc = None
shutil.rmtree(self.tempdir)
def url(self, path):
return "http://localhost:%s/%s" % (self.portnum, path.lstrip('/'))
def proxy_url(self):
return "http://localhost:%s" % self.proxy_portnum