Hoo*_*ked 4 python subprocess signals
给出一个外部程序,对于这个例子是python target.py:
import time, itertools
A = itertools.count()
while True:
time.sleep(.1)
print A.next()
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种运行命令的方法,我们可以假设除了启动和停止之外我无法控制5秒钟.那时,我想暂停执行(类似于control-ZLinux,这是我的目标平台),运行一些内部代码然后继续执行子进程.到目前为止我已经有了
import subprocess, signal, time
cmd = "python target.py"
P = subprocess.Popen(cmd,shell=True)
while True:
time.sleep(5)
signal.pause(P) # Not the correct way to suspend P
print "doing something"
signal.wakeup(P) # What is called here?
Run Code Online (Sandbox Code Playgroud)
你也可以使用psutil并避免看起来很可怕的os.kill:
import psutil, time, subprocess
cmd = "python target.py"
P = subprocess.Popen(cmd,shell=True)
psProcess = psutil.Process(pid=P.pid)
while True:
time.sleep(5)
psProcess.suspend()
print 'I am proactively leveraging my synergies!'
psProcess.resume()
Run Code Online (Sandbox Code Playgroud)
由于您使用的是Linux,因此可以使用以下reader.py:
import subprocess, signal, time, os
cmd = "python target.py"
P = subprocess.Popen(cmd,shell=True)
while True:
time.sleep(5)
os.kill(P.pid, signal.SIGSTOP)
print "doing something"
os.kill(P.pid, signal.SIGCONT)
Run Code Online (Sandbox Code Playgroud)