The*_*mer 7 stdin subprocess python-3.x
那么如何使用 stdin 将二进制数据传递给我想要运行的可执行命令呢subprocess.run()?
该文档对于使用标准输入将数据传递给外部可执行文件非常模糊。我正在使用 python3 在 linux 机器上工作,我想调用dd of=/somefile.data bs=32(如果我正确理解手册页,它会从 stdin 获取输入)并且我有二进制数据,bytearray我想通过 stdin 传递给命令,这样我就可以不必将其写入临时文件并dd使用该文件作为输入来调用。
我的要求只是将我所拥有的数据传递bytearray给dd要写入磁盘的命令。使用以下方法实现此目的的正确方法是什么subprocess.run()?
编辑:我的意思是这样的:
ba = bytearray(b"some bytes here")
#Run the dd command and pass the data from ba variable to its stdin
Run Code Online (Sandbox Code Playgroud)
您可以通过直接调用将一个命令的输出传递给另一个命令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()
Run Code Online (Sandbox Code Playgroud)
据我所知,这对于命令 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3865 次 |
| 最近记录: |