从 python 启动和停止外部进程
Start and Stop external process from python
有没有办法从 python 启动和停止进程?我说的是一个持续的过程,我在通常 运行ning 时用 ctrl+z 停止。我想启动这个过程,等待一段时间然后杀死它。我正在使用 linux.
this question 不像我的,因为在那里,用户只需要 运行 这个过程。我需要 运行 它并停止它。
也许你可以使用 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())
您可以使用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)
I want to start the process, wait for some time and then kill it.
#!/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
有没有办法从 python 启动和停止进程?我说的是一个持续的过程,我在通常 运行ning 时用 ctrl+z 停止。我想启动这个过程,等待一段时间然后杀死它。我正在使用 linux.
this question 不像我的,因为在那里,用户只需要 运行 这个过程。我需要 运行 它并停止它。
也许你可以使用 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())
您可以使用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)
I want to start the process, wait for some time and then kill it.
#!/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