Bash command runs in shell, but not via Python subprocess

huangapple go评论60阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年7月24日 15:56:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76752415.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定