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)
我用bash作为进程在Ubuntu中测试了这段代码,它按预期工作。在你的评论中,你注意到你得到了file not found错误。您可以尝试将pidof的完整路径放入check_output调用中。这可以从终端使用which pidof找到。我的系统代码会变成
您可能想看看^{} 模块,它可以从Python运行shell命令。例如,看看this answer。然后您可以得到stdout from the shell command to a variable。我想您需要^{} shell命令。在
基本思路如下:
我用
^{pr2}$bash
作为进程在Ubuntu中测试了这段代码,它按预期工作。在你的评论中,你注意到你得到了file not found
错误。您可以尝试将pidof
的完整路径放入check_output
调用中。这可以从终端使用which pidof
找到。我的系统代码会变成你的道路可能不同。在windows上,将
shell=True
添加到check_output
参数可以解决这个问题,但我认为这与Linux无关。在非常感谢你的帮助,威尔·哈特,我终于成功了。需要更改一些细节,因为脚本一直说“output”没有定义。现在是这样的:
相关问题 更多 >
编程相关推荐