gpt4 book ai didi

python - 写入 Python subprocess.Popen 对象的文件描述符 3

转载 作者:太空狗 更新时间:2023-10-29 21:04:11 31 4
gpt4 key购买 nike

如何写入 subprocess.Popen 对象的文件描述符 3?

我正在尝试使用 Python 在以下 shell 命令中完成重定向(不使用命名管道):

$ gpg --passphrase-fd 3 -c 3<passphrase.txt < filename.txt > filename.gpg

最佳答案

子进程 proc 继承在父进程中打开的文件描述符。因此,您可以使用 os.open 打开 passphrase.txt 并获取其关联的文件描述符。然后您可以构造一个使用该文件描述符的命令:

import subprocess
import shlex
import os

fd=os.open('passphrase.txt',os.O_RDONLY)
cmd='gpg --passphrase-fd {fd} -c'.format(fd=fd)
with open('filename.txt','r') as stdin_fh:
with open('filename.gpg','w') as stdout_fh:
proc=subprocess.Popen(shlex.split(cmd),
stdin=stdin_fh,
stdout=stdout_fh)
proc.communicate()
os.close(fd)

要从管道而不是文件中读取,您可以使用 os.pipe:

import subprocess
import shlex
import os

PASSPHRASE='...'

in_fd,out_fd=os.pipe()
os.write(out_fd,PASSPHRASE)
os.close(out_fd)
cmd='gpg --passphrase-fd {fd} -c'.format(fd=in_fd)
with open('filename.txt','r') as stdin_fh:
with open('filename.gpg','w') as stdout_fh:
proc=subprocess.Popen(shlex.split(cmd),
stdin=stdin_fh,
stdout=stdout_fh )
proc.communicate()
os.close(in_fd)

关于python - 写入 Python subprocess.Popen 对象的文件描述符 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6050187/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com