【问题标题】:Python os.system grep different results than bash grep [duplicate]Python os.system grep 与 bash grep 的结果不同 [重复]
【发布时间】:2020-05-19 21:46:18
【问题描述】:

我正在将 bash 脚本转换为 python,但是在 python 中执行此操作时:

cmd = r"grep 'name' somefile.log | grep -v 'result=""' | grep -v result='is\ OK'"
results_str = os.system(cmd)
print (results_str,"\n")

我没有得到任何 grep 的输出。如果我从命令行/bash 运行它,我会得到

grep 'name' somefile.log | grep -v 'result=""' | grep -v result='is\ OK'
name="blah", result="the thing I'm trying to grep", action="", info=""

我的 python grep 出了什么问题?

【问题讨论】:

标签: python


【解决方案1】:

使用 - os.popen()

os.popen() 让您可以控制进程的输入或输出文件流。 os.system() 没有。如果不需要访问进程的 I/O,可以使用os.system() 为简单起见。

所以你修改后的代码将是 -

cmd = r"grep 'name' somefile.log | grep -v 'result=""' | grep -v result='is\ OK'"
results_str = os.popen(cmd)
print (results_str,"\n")

【讨论】:

  • os.popen() 也不返回标准输出。
  • os.open(cmd) 给出错误<os._wrap_close object at 0x7f9040176da0>,不知道这是什么意思
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多