写入Python subprocess.Popen对象的文件描述符3
我该如何向一个subprocess.Popen对象的文件描述符3写入数据呢?
我想用Python实现下面这个shell命令的重定向(不使用命名管道):
$ gpg --passphrase-fd 3 -c 3<passphrase.txt < filename.txt > filename.gpg
1 个回答
8
子进程 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)