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
相关产品推荐
相关产品推荐

