python - 有什么方法可以在不使用 shell=True 的情况下使用子进程模块在 Python 中执行管道命令?

标签 python bash

我想从 Python 运行管道命令行 linux/bash 命令,它首先将 tars 文件打包,然后拆分 tar 文件。该命令在 bash 中看起来像这样:

> tar -cvf - path_to_archive/* | split -b 20m -d -a 5 - "archive.tar.split"

我知道我可以使用子进程执行它,通过设置 shell=True,并将整个命令作为字符串提交,如下所示:

import subprocess    

subprocess.call("tar -cvf - path_to_archive/* | split -b 20m -d -a 5 - 'archive.tar.split'", shell=True)

...但出于安全原因,我想找到一种方法来跳过“shell=True”部分,(它采用字符串列表而不是完整的命令行字符串,并且无法处理管道字符正确)。在 Python 中有解决这个问题的方法吗?即,是否有可能以某种方式或其他解决方案设置链接管道?

最佳答案

如果你想避免使用 shell=True,你可以手动使用 subprocess pipes .

from subprocess import Popen, PIPE
p1 = Popen(["tar", "-cvf", "-", "path_to_archive"], stdout=PIPE)
p2 = Popen(["split", "-b", "20m", "-d", "-a", "5", "-", "'archive.tar.split'"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

请注意,如果您不使用 shell,您将无法访问 * 等通配符的扩展。相反,您可以使用 glob 模块。

关于python - 有什么方法可以在不使用 shell=True 的情况下使用子进程模块在 Python 中执行管道命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4368818/

相关文章:

python - 我可以在 Sphinx 的目录中添加水平条吗?

python - snappy/snappymodule.cc(31) : fatal error C1083: Cannot open include file: 'snappy-c.h' : No such file or directory

python - 在 Windows 上设置 Python 语言环境的正确方法是什么?

python - Django Modal save() 函数未实现,使用 google app engine dev server 和 mysql

python - 如何将 Poisson CDF 编写为 Python Polars 表达式

linux - MV : cannot overwrite directory with non-directory

bash - gcloud:是否可以根据当前文件夹更改默认项目?

linux - Bash循环中的计数器增量不起作用

bash - 使用脚本查看所有文件夹和子文件夹

linux - bash | curl | curl 2 个 URL 然后停止