【问题标题】:PYTHON - grep command: wrong output, exit status 2PYTHON - grep 命令:错误输出,退出状态 2
【发布时间】:2022-11-10 18:04:24
【问题描述】:

我试图在子文件夹中的特定大文件 (GB) 中查找模式

我正在运行 Python 代码。

  1. 试过....
    FILE_PATH=/folder1/FILE.txt - OK, absolute path
    
    with open (FILE_PATH, "r") as FILE:
      for index, x in enumerate(FILE):
        if re.findall(".*TEXT.*", x):
          ...takes too much time...
    
    1. 另一种方式

    在终端的 Bash 中:

    grep -a 'TEXT' /folder1/FILE.txt - output OK as desired
    

    Python代码:

    FILE_PATH=/folder1/FILE.txt - OK, absolute path
    
    STATUS=(subprocess.check_output("grep -a \'TEXT\' " + str(FILE_PATH.encode()), shell=True)).rstrip('\n')
    
    I get this output in terminal
    ...: Command 'grep -a 'TEXT' b'/folder1/FILE.txt'' returned non-zero status 2
    

    请问有什么建议吗?

    如何在 Python 中对带有变量(文件路径)的二进制/文本文件运行 Bash GREP 命令并将 grep 输出存储到 Python 中的变量中

【问题讨论】:

    标签: python grep binary subprocess encode


    【解决方案1】:

    您可以尝试使用 os.popen(),它应该模仿并返回您在使用 bash 命令时看到的结果:

    import os
    FILE_PATH = "/folder1/FILE.txt"
    results = os.popen(f"grep -a 'TEXT' {FILE_PATH}").read()
    print(results)
    

    【讨论】:

      猜你喜欢
      • 2018-09-18
      • 2020-07-08
      • 2020-03-05
      • 2022-08-07
      • 2014-06-18
      • 1970-01-01
      • 2021-01-25
      • 2021-10-29
      • 2021-05-31
      相关资源
      最近更新 更多