Python3 使用 subprocess.run() 时如何将二进制数据传递给标准输入?

Python3 how to pass binary data to stdin when using subprocess.run()?

那么如何使用 stdin 将二进制数据传递到我想使用 subprocess.run() 运行 的可执行命令?

文档中关于使用标准输入将数据传递给外部可执行文件的内容非常模糊。我正在使用 python3 在 linux 机器上工作,我想调用 dd of=/somefile.data bs=32 (如果我正确理解手册页,它会从 stdin 获取输入)并且我有二进制数据 bytearray 我想通过 stdin 传递给命令,这样我就不必将它写入临时文件并使用该文件作为输入来调用 dd

我的要求只是将我在 bytearray 中的数据传递给要写入磁盘的 dd 命令。使用 subprocess.run() 和 stdin 实现此目的的正确方法是什么?

编辑:我的意思如下:

ba = bytearray(b"some bytes here")
#Run the dd command and pass the data from ba variable to its stdin

您可以通过直接调用 Popen 将一条命令的输出传递给另一条命令。

file_cmd1 = <your dd command>
file_cmd2 = <command you want to pass dd output to>

proc1 = Popen(sh_split(file_cmd1), stdout=subprocess.PIPE)
proc2 = Popen(file_cmd2, [shell=True], stdin=proc1.stdout, stdout=subprocess.PIPE)
proc1.stdout.close()

据我所知,这在命令 1 的字节输出上工作得很好。

在您的情况下,当您只想将数据传递给进程的 stdin 时,您最想做的是以下操作:

out = bytearray(b"Some data here")
p = subprocess.Popen(sh_split("dd of=/../../somefile.data bs=32"), stdin=subprocess.PIPE)
out = p.communicate(input=b''.join(out))[0]
print(out.decode())#Prints the output from the dd

按照 OP 的要求,专门针对 subprocess.run() 的标准输入,使用 input 如下:

#!/usr/bin/python3
import subprocess

data = bytes("Hello, world!", "ascii")

p = subprocess.run(
    "cat -", # The - means 'cat from stdin'
    input=data,
    # stdin=... <-- don't use this
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
)

print(p.stdout.decode("ascii"))
print(p.returncode)

# Hello, world!
# 0