如何从 python 执行一组链接的 linux 命令

Wes*_*cts 2 shell python

以下是我想逐字执行的 shell 命令示例。在 python 中以任何方式执行此操作(即类似于 ruby​​ 中的 %x{command} 构造,它将接受您提供的任何内容..

kill -9 $(ps -ef | grep java | grep TaskTracker | awk '{print $2}')
Run Code Online (Sandbox Code Playgroud)

这里的诀窍是它有链式管道 - 所以这在 AFAICT 中表现不佳,例如 popen。

小智 10

该命令需要 shell 功能,包括命令替换和管道,因此您应该shell=Truesubprocess.call()调用中使用。只要您在 shell 中运行它,它就应该可以正常工作。所以:

from subprocess import call

call("kill -9 $(ps -ef | grep java | grep TaskTracker | awk '{print $2}')",
      shell=True)
Run Code Online (Sandbox Code Playgroud)