【问题标题】:Start and Stop external process from python从 python 启动和停止外部进程
【发布时间】:2015-11-07 17:54:51
【问题描述】:
有没有办法从 python 启动和停止进程?我说的是一个在正常运行时用 ctrl+z 停止的持续过程。我想启动该过程,等待一段时间然后将其终止。我用的是linux。
this question 不像我的,因为在那里,用户只需要运行该进程。我需要运行它并停止它。
【问题讨论】:
标签:
python
linux
subprocess
external-process
【解决方案1】:
我想启动进程,等待一段时间然后终止它。
#!/usr/bin/env python3
import subprocess
try:
subprocess.check_call(['command', 'arg 1', 'arg 2'],
timeout=some_time_in_seconds)
except subprocess.TimeoutExpired:
print('subprocess has been killed on timeout')
else:
print('subprocess has exited before timeout')
见Using module 'subprocess' with timeout
【解决方案2】:
您可以使用os.kill 函数发送-SIGSTOP (-19) 和-SIGCONT (-18)
示例(未验证):
import signal
from subprocess import check_output
def get_pid(name):
return check_output(["pidof",name])
def stop_process(name):
pid = get_pid(name)
os.kill(pid, signal.SIGSTOP)
def restart_process(name):
pid = get_pid(name)
os.kill(pid, signal.SIGCONT)
【解决方案3】:
也许你可以使用Process 模块:
from multiprocessing import Process
import os
import time
def sleeper(name, seconds):
print "Sub Process %s ID# %s" % (name, os.getpid())
print "Parent Process ID# %s" % (os.getppid())
print "%s will sleep for %s seconds" % (name, seconds)
time.sleep(seconds)
if __name__ == "__main__":
child_proc = Process(target=sleeper, args=('bob', 5))
child_proc.start()
time.sleep(2)
child_proc.terminate()
#child_proc.join()
#time.sleep(2)
#print "in parent process after child process join"
#print "the parent's parent process: %s" % (os.getppid())