【问题标题】:tail command not giving correct answer for subprocess.Popentail 命令没有为 subprocess.Popen 给出正确答案
【发布时间】:2018-11-01 21:31:51
【问题描述】:

当通过终端运行以下命令时,它给出了正确的输出,即不包括顶部的 6 行,显示 data.out 的剩余行。

tail -n +6 data.out

但是当通过subprocess.Popen 处理相同的命令时,如下代码所示:

fin = open('data.out')
fout = file('data1.out','w')
line = 6
lineno = "-n +" + str(line)
p2 = subprocess.Popen(["tail",lineno], stdin=fin, stdout=fout)
errcode = p2.wait()
fin.close()
fout.close()

这是在 data1.out 文件中存储data.out 的最后 6 行,这是不正确的。这是存储tail -n 6 data.out 的输出,而不是给定和预期的tail -n +6 data.out

【问题讨论】:

    标签: python subprocess pipe popen


    【解决方案1】:

    不要将多参数与列表参数混合

    lineno = "-n +" + str(line)  # wrong: 2 arguments seen as one
    p2 = subprocess.Popen(["tail",lineno], stdin=fin, stdout=fout)
    

    这里有 2 个参数,+line 部分可能会被 tail 忽略。相反,只需为每个列表项传递一个参数:

    p2 = subprocess.Popen(["tail","-n","+"+str(line)], stdin=fin, stdout=fout)
    

    使用format 可能更清楚:

    p2 = subprocess.Popen(["tail","-n","+{}".format(line)], stdin=fin, stdout=fout)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 2015-06-23
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      相关资源
      最近更新 更多