我目前正在 Raspberry Pi 上运行 OpenELEC (XBMC) 安装,并安装了一个名为“Hyperion”的工具,该工具负责连接的流光溢彩。在 Python 编程方面,我完全是个菜鸟,所以这是我的问题:
如何运行一个脚本来检查名称中包含特定字符串的进程是否正在运行,并且:
- 在进程运行时终止进程
- 在进程未运行时启动进程
这样做的目标是拥有一个切换流光溢彩的脚本。知道如何实现这一目标吗?
非常感谢您的帮助@will-hart,我终于让它工作了。需要更改一些细节,因为脚本一直说“输出”未定义。下面是它现在的样子:
#!/usr/bin/env python
import subprocess
from subprocess import call
try:
subprocess.check_output(["pidof", "hyperiond"])
except subprocess.CalledProcessError:
subprocess.Popen(["/storage/hyperion/bin/hyperiond.sh", "/storage/.config/hyperion.config.json"])
else:
subprocess.call(["killall", "hyperiond"])
您可能想看看subprocess
可以从 Python 运行 shell 命令的模块。例如,看看这个答案。然后,您可以从 shell 命令获取 stdout 到一个变量。我怀疑您将需要pidof
shell 命令。
基本思想是这样的:
import subprocess
try:
subprocess.check_output(["pidof", "-s", "-x", "hyperiond"])
except subprocess.CalledProcessError:
# spawn the process using a shell command with subprocess.Popen
subprocess.Popen("hyperiond")
else:
# kill the process using a shell command with subprocess.call
subprocess.call("kill %s" % output)
我已经在 Ubuntu 中使用bash
as 过程测试了这段代码,它按预期工作。在您的评论中,您注意到您遇到了file not found
错误。您可以尝试将完整路径pidof
放入您的check_output
通话中。这可以which pidof
从终端中找到。我的系统的代码将变成
subprocess.check_output(["/bin/pidof", "-s", "-x", "hyperiond"])
你的路径可能不同。在 Windows 上添加参数shell=True
可以check_output
解决这个问题,但我认为这与 Linux 无关。