python 有没有办法用python启动/停止linux进程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1378974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
is there a way to start/stop linux processes with python?
提问by tehryan
I want to be able to start a process and then be able to kill it afterwards
我希望能够启动一个进程,然后能够杀死它
采纳答案by Bastien Léonard
Have a look at the subprocess
module.
You can also use low-level primitives like fork()
via the os
module.
看看subprocess
模块。您还可以使用低级原语,如fork()
通过os
模块。
回答by FeatureCreep
Here's a little python script that starts a process, checks if it is running, waits a while, kills it, waits for it to terminate, then checks again. It uses the 'kill' command. Version 2.6 of python subprocess has a kill function. This was written on 2.5.
这是一个小的 python 脚本,它启动一个进程,检查它是否正在运行,等待一段时间,杀死它,等待它终止,然后再次检查。它使用“kill”命令。python subprocess 2.6版本有kill函数。这是在 2.5 上写的。
import subprocess
import time
proc = subprocess.Popen(["sleep", "60"], shell=False)
print 'poll =', proc.poll(), '("None" means process not terminated yet)'
time.sleep(3)
subprocess.call(["kill", "-9", "%d" % proc.pid])
proc.wait()
print 'poll =', proc.poll()
The timed output shows that it was terminated after about 3 seconds, and not 60 as the call to sleep suggests.
定时输出显示它在大约 3 秒后终止,而不是睡眠调用建议的 60。
$ time python prockill.py
poll = None ("None" means process not terminated yet)
poll = -9
real 0m3.082s
user 0m0.055s
sys 0m0.029s
回答by DigitalRoss
回答by Botond Béres
A simple function that uses subprocess module:
一个使用 subprocess 模块的简单函数:
def CMD(cmd) :
p = subprocess.Popen(cmd, shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=False)
return (p.stdin, p.stdout, p.stderr)
回答by DrFalk3n
see docs for primitive fork() and modules subprocess, multiprocessing, multithreading
请参阅原始 fork() 和模块subprocess、multiprocessing、multithreading 的文档
回答by dcrosta
If you need to interact with the sub process at all, I recommend the pexpect module (link text). You can send input to the process, receive (or "expect") output in return, and you can close the process (with force=True to send SIGKILL).
如果您需要与子流程进行交互,我推荐 pexpect 模块(链接文本)。您可以向进程发送输入,接收(或“期望”)输出作为回报,并且您可以关闭进程(使用 force=True 发送 SIGKILL)。