【问题标题】:subprocess.call - grep -c doesn't return correct valuesubprocess.call - grep -c 不返回正确的值
【发布时间】:2016-03-30 15:31:30
【问题描述】:

我正在尝试使用 python 的 subprocess.call 来执行以下 unix 功能:

grep -c 'Frame:0' file.txt

我的 python 代码如下所示:

frame0Count=int(unix.call("grep -c 'Frame:0' %s"% fileNameVariable,shell=True))

没有发现任何事件,屏幕输出是:

0

但是,frame0Count 变量的值是 1,而不是 0。

谁能解释这是为什么?

谢谢

【问题讨论】:

  • subprocess.call 不返回命令的文本输出,它返回命令是否成功。如果您想要 grep 的输出,请查看 subprocess.check_output
  • 哦,谢谢。我实际上之前尝试过 check_output,但是当没有发现任何事件时出现错误
  • @user1338194 当使用--silent 参数没有返回任何行时,你能不抑制grep 的错误吗?这样你就可以使用@SimonFraser 的建议使用check_output
  • 我根据 Simon 不使用 subprocess.call 的建议找到了解决方案的答案。我张贴作为答案。感谢您的意见。

标签: python unix subprocess


【解决方案1】:

正如西蒙指出我的方法是错误的。为了实现我的目标,我可以执行以下操作:

callStringframe0= unix.Popen('grep -c Frame:0 %s' % fileNameVariable , 
                              stdout=unix.PIPE,
                              stderr=unix.STDOUT, 
                              shell=True)
frame0Count=int(callStringframe0.stdout.read())

这给了我正确的答案。

【讨论】:

    猜你喜欢
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 2010-12-14
    • 2021-01-20
    相关资源
    最近更新 更多