【问题标题】:Use awk in python script在 python 脚本中使用 awk
【发布时间】:2018-05-08 04:22:45
【问题描述】:

我必须在 python 脚本中使用 awk print。

下面我使用的格式

  a = commands.getoutput(" ls -l | awk \'{print $1, $2}\' | awk \'{if(NR>3)print}\'"

我遇到以下错误:

 KeyError: 'print $1, $2'

谁能帮我解决。

【问题讨论】:

  • 列出完整的函数参数。你是在那一行的某处打电话给.format()吗?
  • commands 模块早已被弃用。在 Python 本身中,这些都不难做到。
  • 是的,我正在调用 .format()
  • I have to use awk print inside python script.。不,你没有。这里没有什么是 Python 做不到的。
  • 正如其他人所说,您可以在Python中进行此操作。通过在 shell 管道中调用 awk 来做到这一点是愚蠢的。此外,即使您在 Bash 脚本中或直接在终端中执行此操作,解析 ls 的输出也被认为是不好的做法,如 BashGuide's ParsingLsWhy not parse ls? 中所述。

标签: python linux python-2.7 awk


【解决方案1】:

您的 Awk 脚本可以简单地简化为单个脚本。无论如何,这里没有什么真正需要使用 Awk。

from subprocess import Popen, PIPE
with Popen(["ls", "-l"], stdout=PIPE, universal_newlines=True) as proc:
    for index, line in enumerate(proc.stdout):
        if index <= 2:
            continue
        print(' '.join(line.split()[0:2]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 2013-05-16
    • 2023-03-30
    相关资源
    最近更新 更多