【问题标题】:unable to execute the awk command in python script using subprocess无法使用子进程在 python 脚本中执行 awk 命令
【发布时间】:2018-02-07 01:17:52
【问题描述】:

您好,我正在尝试从 shell 脚本转移到 python

awk -F' ' '{print FILENAME " "$2 " " $3 " " $5}' $text| tail -n+4|head -n -2

在 python 中创建子进程时,出现错误。请问我哪里出错了。我尝试在 F 之后使用转义字符。

c1 = subprocess.Popen(["awk -F' ' '{print FILENAME " "$2 " " $3 " " $5}' {0} | tail -n+4|head -n -2".format(text)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = c1.communicate()
print output

【问题讨论】:

  • 对于c1,您似乎想要传递一个字符串而不是一个列表并使用shell=True 参数——此外,如果您这样做,请确保您信任供应商venue 完全 因为你很容易受到 shell 注入的攻击。否则,您需要在 python 中构建 shell 管道(稍微麻烦一些,但仍然可以)
  • 我也试过这个 c1 = subprocess.Popen(['awk', "-F' '", "'{print FILENAME " "$2 " " $3 " " $5}'", { 0}].format(text)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) c2 = subprocess.Popen(['tail', '-n+4'], stdin=c1 .stdout, stdout=subprocess.PIPE) c3 = subprocess.Popen(['head', '-n', '-2'], stdin=c2.stdout, stdout=subprocess.PIPE) 输出,err = c3.communicate ()
  • 我试过 shell=True,我得到一个错误 KeyError: 'print FILENAME $2 $3 $5'

标签: python awk subprocess


【解决方案1】:

我能够解决这个问题

first = "awk -F' ' '{print "+venue+" $2 "+"$3 "+"$5}' "+venue1+" | tail -n+4|head -n -2"

c1 = subprocess.Popen([first], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

x= c1.communicate()[0]

输出是 xyz 我需要 x、y 和 z 之间的空间

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 2022-10-19
    • 2018-04-25
    相关资源
    最近更新 更多