You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash命令可在Shell运行但无法通过Python subprocess执行的问题

Python执行带管道和进程替换的Bash命令报错问题

问题场景

我尝试在Python中运行以下Bash命令:

import subprocess

command = 'tar -vcz -C /mnt/20TB_raid1  Illumina_Sequencing_Data | pigz | tee >(md5sum > "md5sum_Illumina_Sequencing_Data.txt") | split -b 50G - /mnt/4TB_SSD/Illumina_Sequencing_Data.tar.gz.part-'

subprocess.run(command.split(" "))

该命令直接在Shell中运行完全正常,但通过Python执行时抛出错误:

tar: 50G: Invalid blocking factor
Try 'tar --help' or 'tar --usage' for more information.

从错误信息来看,split的-b 50G参数被错误当成了tar的参数,后续命令逻辑被忽略。

问题原因

subprocess.run(command.split(" "))的处理方式完全错误:

  • 管道(|)、进程替换(>(...))都是Shell专属的语法,需要Shell来解析处理,不是单个命令的参数。
  • 直接按空格拆分字符串后,所有内容都被当成tar命令的参数传入,自然会出现参数解析错误。

解决方法

让subprocess调用Shell来完整解析整个命令,不要手动拆分参数:

import subprocess

command = 'tar -vcz -C /mnt/20TB_raid1  Illumina_Sequencing_Data | pigz | tee >(md5sum > "md5sum_Illumina_Sequencing_Data.txt") | split -b 50G - /mnt/4TB_SSD/Illumina_Sequencing_Data.tar.gz.part-'

# 通过shell=True让Bash负责解析命令中的管道、进程替换等语法
subprocess.run(command, shell=True)

额外说明

  • 使用shell=True时,要确保命令内容是可信的,避免不可信输入导致Shell注入风险。
  • 如果需要指定特定Shell(比如bash,因为进程替换是bash特性),可以加上executable='/bin/bash'参数:
subprocess.run(command, shell=True, executable='/bin/bash')

内容的提问来源于stack exchange,提问作者justinian482

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 04:32:50