擅长:python、mysql、java
<p>可以使用<code>pidof</code>到<a href="https://docs.python.org/2/library/subprocess.html#subprocess.check_output" rel="noreferrer">subprocess.check_output</a>按名称获取进程的pid:</p>
<pre><code>from subprocess import check_output
def get_pid(name):
return check_output(["pidof",name])
In [5]: get_pid("java")
Out[5]: '23366\n'
</code></pre>
<p><code>check_output(["pidof",name])</code>将作为<code>"pidof process_name"</code>,<em>运行命令,如果返回代码为非零,则会引发调用的进程错误。</em></p>
<p>要处理多个条目并转换为int,请执行以下操作:</p>
<pre><code>from subprocess import check_output
def get_pid(name):
return map(int,check_output(["pidof",name]).split())
</code></pre>
<p>在[21]中:获取pid(“chrome”)</p>
<pre><code>Out[21]:
[27698, 27678, 27665, 27649, 27540, 27530, 27517, 14884, 14719, 13849, 13708, 7713, 7310, 7291, 7217, 7208, 7204, 7189, 7180, 7175, 7166, 7151, 7138, 7127, 7117, 7114, 7107, 7095, 7091, 7087, 7083, 7073, 7065, 7056, 7048, 7028, 7011, 6997]
</code></pre>
<p>或者通过<code>-s</code>标志获取单个pid:</p>
<pre><code>def get_pid(name):
return int(check_output(["pidof","-s",name]))
In [25]: get_pid("chrome")
Out[25]: 27698
</code></pre>