给出一个外部程序,在本例中是python target.py
target.py
import time, itertools
A = itertools.count()
while True:
time.sleep(.1)
print A.next()我正在寻找一种运行该命令的方法,我们可以假设除了启动和停止之外,我无法控制该命令5秒。此时,我想挂起执行(类似于我的目标平台linux上的control-Z ),运行一些内部代码,然后继续执行子进程。到目前为止我有
reader.py
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?发布于 2013-09-24 15:03:38
由于您是在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)发布于 2014-11-19 00:50:03
您也可以使用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()发布于 2018-03-28 02:35:37
我们可以使用子进程的send_signal函数。
import subprocess
import signal
import time
p = subprocess.Popen(['mpg123', '-C', 'music.mp3'])
time.sleep(3)
print('stop')
p.send_signal(signal.SIGSTOP)
time.sleep(3)
print('continue')
p.send_signal(signal.SIGCONT)
time.sleep(3)
p.terminate()https://stackoverflow.com/questions/18984666
复制相似问题