英文:
Bash command runs in shell, but not via Python subprocess
问题
我想在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(" "))
当我运行这段代码时,出现以下错误:
tar: 50G: Invalid blocking factor
Try 'tar --help' or 'tar --usage' for more information.
然而,当我直接在shell中运行此命令时,它没有任何问题。看起来好像某些代码被忽略了,因为它认为split
的-b标志被解析为tar?
英文:
I want to run the following Bash command in Python:
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(" "))
When I run this code I get the following error:
tar: 50G: Invalid blocking factor
Try 'tar --help' or 'tar --usage' for more information.
However, when I run this command in the shell directly it run without any issues. It looks like some code is ignored as it thinks the split
-b flag is parsed to tar?
答案1
得分: 2
这是管道导致问题。
默认情况下,run
函数直接运行单个命令。它不使用 shell 来运行命令。而管道是 shell 的一种特性,由 shell 自己处理。重定向和任何类型的替代都是一样的。
此外,由于你在 Python 中拆分了命令,你会将管道符号和所有管道命令作为实际参数传递给 tar
命令。
如果你想使用管道,你需要调用一个 shell。
英文:
It's the piping that causes the problem.
By default the run
function runs a single command directly. It does not use a shell to run the command. And piping is a shell thing, it's handled all by the shell itself. Same with redirection and any kind of substitution.
Furthermore, since you split the command in Python, you will pass the pipe signs and all the piped commands as actual arguments to the tar
command.
You need to invoke a shell if you want to use piping.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论