Python subprocess:如何将一个进程的输出管道到另一个进程的输入
这是如何启动一个进程,其输出管道到另一个子进程输入,其输出传递给 Python 的示例。
在此示例中,进程将使用 xz 从 input.txt.xz 流式解压数据,然后传递给 sha512sum 计算未压缩输入数据的 SHA512 校验和。
等效的 shell 命令是 xz --decompress --stdout input.txt.xz | sha512sum。
完整源代码
pipe_example.py
import subprocess
file_path = "input.txt.xz"
# Decompress the file on the fly and compute the SHA512 checksum
decompress_process = subprocess.Popen(['xz', '--decompress', '--stdout', file_path], stdout=subprocess.PIPE)
checksum_process = subprocess.run(['sha512sum'], stdin=decompress_process.stdout, stdout=subprocess.PIPE, text=True)
decompress_process.stdout.close()
decompress_process.wait()
# Extract the SHA512 checksum from the command output
sha512sum = checksum_process.stdout.split()[0]
print(sha512sum)Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow