awk:1:意外的角色'''错误

时间:2017-05-31 06:23:11

标签: python bash awk subprocess

我正在尝试通过python subprocess

运行此命令
cat /etc/passwd | awk -F':' '{print $1}'

我所做的是通过运行两个子进程运行命令。

1st:哪个会获取结果,即。 cat / etc / passwd

第二:第一个的输出将作为输入提供给第二个 awk -F':' ' {print $ 1}'

以下是代码:

def executeCommand(self, command, filtercommand):
   cmdout = subp.Popen(command, stdout=subp.PIPE)
   filtered = subp.Popen(filtercommand, stdin=cmdout.stdout, stdout=subp.PIPE)
   output, err = filtered.communicate()
   if filtered.returncode is 0:
      logging.info("Result success,status code %d", filtered.returncode)
      return output
   else:
      logging.exception("ErrorCode:%d %s", filtered.returncode, output)
      return False

其中,

command = [' sudo',' cat',' / etc / shadow']

filtercommand = [' awk'," -F':'","' {print $ 1}'",' |',' uniq']

错误:

awk: 1: unexpected character ''' error 

我如何创建传递给函数的filercommand列表:

filtercommand=["awk","-F\':\'", "\'{print $1}\'", '|', 'uniq']

1 个答案:

答案 0 :(得分:0)

您可以直接使用subprocess.Popen使用管道命令,并获取输出和错误:

import subprocess

cmd = "cat /etc/passwd | awk -F':' 'NF>2 {print $1}'"

p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
output, err = p.communicate()

print output
print err

但是请注意cat在上面的管道命令中完全没用,因为awk可以直接对文件进行操作,如下所示:

cmd = "awk -F':' 'NF>2 {print $1}' /etc/passwd"
相关问题