无法使用 python 执行 bash 命令

Failed to execute bash commands using python

我想 运行 bash 使用 python 函数的命令如下:

def ExtractData(data, type_list):

    for i in type_list :

        os.system("sed -n '/\t{}\t/p' {} > raw_extract_{}.tsv".format(i, data, i))
        os.system("cut -d$'\t' -f2,4,8,46,63,65,66 raw_extract_{}.tsv > extract_{}_reduced.tsv".format(i, i))

    return "Done !"


ExtractData("data.tsv", [2201, 2202])

然而,即使 "sed" 部分工作正常,我使用 "cut" 命令没有得到任何结果,它返回退出状态 1。我尝试在控制台中自己输入它,但我得到了预期的结果,所以命令是正确的。有人能看出这个程序有什么问题吗?

Ps :我知道 os.system 已被弃用,我也尝试了 subprocess.call 但我得到了完全相同的错误。

Python默认使用/bin/sh来执行命令。 运行 你的第二个命令为我生成了以下错误消息:

cut: the delimiter must be a single character Try 'cut --help' for more information.

cut 中,默认分隔符是 \t,因此请尝试 运行 以下命令:

cut -f2,4,8,46,63,65,66 raw_extract_{}.tsv > extract_{}_reduced.tsv

或者,您可以使用命令

/bin/bash -c "cut -d$'\t' -f2,4,8,46,63,65,66 raw_extract_{}.tsv > extract_{}_reduced.tsv"