python - 使用 Python 脚本切换进程(运行时终止,不运行时启动)

标签 python linux shell scripting xbmc

我目前正在 Raspberry Pi 上运行 OpenELEC (XBMC) 安装,并安装了一个名为“Hyperion”的工具来处理连接的流光溢彩。在 Python 编程方面,我完全是菜鸟,所以这是我的问题:

我如何运行一个脚本来检查名称中包含特定字符串的进程是否正在运行,并且:

  • 在进程运行时终止进程
  • 在进程未运行时启动进程

这样做的目标是拥有一个切换流光溢彩的脚本。知道如何实现这一点吗?

最佳答案

您可能想看看 subprocess可以从 Python 运行 shell 命令的模块。例如,看看 this answer .然后您可以获得 stdout from the shell command to a variable .我怀疑您将需要 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 作为进程测试了这段代码,它按预期工作。在您的评论中,您注意到您遇到了 file not found 错误。您可以尝试将 pidof 的完整路径放入您的 check_output 调用中。这可以从终端使用 which pidof 找到。我的系统代码将变成

    subprocess.check_output(["/bin/pidof", "-s", "-x", "hyperiond"])

您的路径可能不同。在 Windows 上,将 shell=True 添加到 check_output 参数可以修复此问题,但我认为这与 Linux 无关。

关于python - 使用 Python 脚本切换进程(运行时终止,不运行时启动),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21277731/

相关文章:

python - Pyexcel 保存到字典吗?

linux - 如何从 docker 容器内的主机 bash 脚本运行并保留在容器中的 bash 中

python - 使用 python 将外部文件中的数据保存到列表中

linux - sendmail:为每封邮件指定 SMTP 服务器和 TLS 选项

linux - 在 ssh 中运行 ls 命令

mysql - 使用shell脚本向远程MYSQL数据库插入数据

java - 用于 Android 应用程序的 Python

python - matplotlib savefig() 空白 - show() 不是

python - text.usetex : True in matplotlib 有什么好处

linux - sort -u 无法删除重复行