【问题标题】:awk: 1: unexpected character ''' errorawk:1:意外字符'''错误
【发布时间】:2017-10-31 19:24:07
【问题描述】:

我正在尝试通过 python 子进程运行此命令

cat /etc/passwd | awk -F':' '{print $1}'

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

第一个:它将获取结果,即。 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']

【问题讨论】:

  • "'{print $1}'" 中不需要单引号。只需删除它们。另外"-F""':'"必须是两个独立的参数,后者也不需要单引号。
  • 尝试不使用单引号会抛出 awk: cannot open | (No such file or directory)
  • | 不是命令行参数,它是一个 shell 重定向。您不能以这种方式使用它。您必须将awk 的标准输出重新连接到uniq 的标准输入,就像将cat 的标准输出重新连接到awk 的标准输入一样。顺便说一句,你可以在没有cat 的情况下使用sudo awk -F ':' '{print $1}' /etc/shadow
  • 正如我之前所说,您不需要在分隔符周围加上单引号 :.
  • 你不能在 Popen 构造函数中使用最后一个filtercommandshell=False

标签: python bash awk subprocess


【解决方案1】:

您可以使用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"

【讨论】:

    猜你喜欢
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 2012-01-21
    • 2022-11-07
    相关资源
    最近更新 更多