<p>您可能想看看<a href="http://docs.python.org/2/library/subprocess.html" rel="nofollow noreferrer">^{<cd1>}</a>模块,它可以从Python运行shell命令。例如,看看<a href="https://stackoverflow.com/questions/89228/calling-an-external-command-in-python">this answer</a>。然后您可以得到<a href="https://stackoverflow.com/questions/4514751/pipe-subprocess-standard-output-to-a-variable">stdout from the shell command to a variable</a>。我想您需要<a href="http://unixhelp.ed.ac.uk/CGI/man-cgi?pidof" rel="nofollow noreferrer">^{<cd2>}</a>shell命令。在</p>
<p>基本思路如下:</p>
<pre><code>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)
</code></pre>
<p>我用<code>bash</code>作为进程在Ubuntu中测试了这段代码,它按预期工作。在你的评论中,你注意到你得到了<code>file not found</code>错误。您可以尝试将<code>pidof</code>的完整路径放入<code>check_output</code>调用中。这可以从终端使用<code>which pidof</code>找到。我的系统代码会变成</p>
^{pr2}$
<p>你的道路可能不同。在windows上,将<code>shell=True</code>添加到<code>check_output</code>参数可以解决这个问题,但我认为这与Linux无关。在</p>