如何在python中执行awk命令

时间:2017-12-04 09:13:10

标签: python awk

我正在尝试在python中运行以下awk命令,但是我收到与引号相关的语法错误:

import subprocess
COMMAND = "df /dev/sda1 | awk /'NR==2 {sub("%","",$5); if ($5 >= 80) {printf "Warning! Space usage is %d%%", $5}}"

subprocess.call(COMMAND, shell=True)

我试图逃避引号,但我仍然遇到同样的错误。

3 个答案:

答案 0 :(得分:2)

由于您同时拥有'''""",因此您可能希望将'"放在字符串周围。

import subprocess
COMMAND = '''"df /dev/sda1 | awk /'NR==2 {sub("%","",$5); if ($5 >= 80) {printf "Warning! Space usage is %d%%", $5}}"'''

subprocess.call(COMMAND, shell=True)

此外似乎也有相关的答案:awk commands within python script

答案 1 :(得分:1)

试试这个:

import subprocess
COMMAND="df /dev/sda1 | awk 'NR==2 {sub(\"%\",\"\",$5); if ($5 >= 80) {printf \"Warning! Space usage is %d%%\", $5}}'"

subprocess.Popen(COMMAND,stdin=subprocess.PIPE,stdout=subprocess.PIPE, shell=True).stdout.read()

答案 2 :(得分:1)

出于部署目的,我正在编写一个python脚本,该脚本的一部分是明确终止该进程,如果该进程未成功停止。

下面是实际执行的python代码 查找名为myApplication的进程的processId ps -ef | grep myApplication | grep -v grep | awk {'print $2'} 然后执行 kill -9 PID // PID是先前命令的输出

  import subprocess, signal
  def killApplicationProcessIfStillRunning(app_name):
  p1 = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE)
  p2 = subprocess.Popen(['grep', app_name],stdin=p1.stdout, stdout=subprocess.PIPE)
  p3 = subprocess.Popen(['grep', '-v' , 'grep'],stdin=p2.stdout, stdout=subprocess.PIPE)
  p4 = subprocess.Popen(['awk', '{print $2}'],stdin=p3.stdout, stdout=subprocess.PIPE)
  out, err = p4.communicate()
  if out:
   print 'Attempting to kill '+app_name +' process with PID ' +out.splitlines()[0]
   os.kill(int(out.splitlines()[0]),signal.SIGKILL)

现在将上述方法调用为

killApplicationProcessIfStillRunning(myApplication)

希望它对某人有帮助。