子
proc进程继承在父进程中打开的文件描述符。因此,您可以
os.open用来打开passphrase.txt并获取其关联的文件描述符。然后,您可以构造一个使用该文件描述符的命令:
import subprocessimport shleximport osfd=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 subprocessimport shleximport osPASSPHRASE='...'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)


