如何写入subprocess.Popen对象的文件描述符3?
我正在尝试使用Python完成以下shell命令中的重定向(不使用命名管道):
$ gpg --passphrase-fd 3 -c 3<passphrase.txt < filename.txt > filename.gpg
Run Code Online (Sandbox Code Playgroud)
子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)
Run Code Online (Sandbox Code Playgroud)
要从管道而不是文件中读取,您可以使用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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4858 次 |
| 最近记录: |