Python subprocess.check_output 转换为 windows

标签 python linux subprocess zgrep

我写了一些在 Linux 机器上运行良好但不能在 Windows 上运行的代码。

import subprocess
import pandas as pd
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

def zgrep_data(f, string='', index='TIMESTAMP'):
    if string == '':
        out = subprocess.check_output(['zgrep', string, f])
        grep_data = StringIO(out)    
        data= pd.read_csv(grep_data, sep=',', header=0)

    else:
        col_out = subprocess.check_output(['zgrep', index, f])
        col_data = StringIO(col_out)
        columns = list(pd.read_csv(col_data, sep=','))

        out = subprocess.check_output(['zgrep', string, f])
        grep_data = StringIO(out)    
        data= pd.read_csv(grep_data, sep=',',names=columns, header=None)

    return data.set_index(index).reset_index()

我收到一个错误: FileNotFoundError: [WinError 2] 系统找不到指定的文件

当我用 os.path.exists(file_path) 检查它时,它返回 true。任何有关如何修改此代码以使其适用于 Python 2 和 3 以及 Windows 和 Linux 的建议都将不胜感激。

最佳答案

此消息仅表示一件事:找不到可执行文件。

这与您的数据文件无关,因为该进程甚至没有运行。

为什么会这样?因为虽然 zgrep 在 Linux 上是标准的,但它在 Windows 上是第三方端口,所以你必须先从 here 安装它

请注意,如果您只想对 csv 文件中的字符串进行 grep,那么使用 zgrep 就有点过分了。使用 native python 方法、读取行(或行,使用 csv 模块)和匹配模式要好得多。您甚至可以在本地打开 .gz 文件。然后它将真正是可移植的。

关于Python subprocess.check_output 转换为 windows,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46495464/

相关文章:

python - 将 Nmap 子进程中的数据直接存储到列表中

python - 设置 matplotlib 极坐标图中中心标记的样式

python - 如何从类文件对象中使用 python mimetypes.guess_type

linux - 在 makefile 中设置共享库的路径以进行编译

linux - 在 Linux 机器上创建和测试 x86-64 ELF 可执行 shellcode

python - CalledProcessError : Command '[' pdftotext', '-layout' , 'coburns.pdf' , '-' ]' returned non-zero exit status 1?

python - 不确定哪些测试用例未通过我的代码

python - Python 在列表推导过程中如何执行?

linux - 如何在命令行中将 markdown 转换为 pdf

python - 如何使用 python 脚本在目录之间进行 "cd"