2011-05-18 135 views
8

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

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

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

我很好奇,想知道这。我不认为这是可能的。 “Popen”对象提供stdout,stdin和stderr句柄。我不知道其他人。 – 2011-05-18 19:49:44

+0

也许是OT,但是您是否知道为GnuPG提供Python API的python-gnupg项目?有关更多信息,请参阅http://code.google.com/p/python-gnupg/。 (披露:这是我的项目) – 2011-05-18 19:55:00

+0

我研究了一些Python gpg包装器,你看起来很可行,但是我目前的项目非常小,我试图最小化依赖关系。 – aaronstacy 2011-05-18 19:58:16

回答

5

子进程的父进程打开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) 
+0

很酷。所以如果我不想将密码保存在一个文件中,我可以创建一个管道,将密码写入它,并使用它的输出fd作为继承的文件描述符,其中gpg将获得密码? – aaronstacy 2011-05-18 21:03:30

+0

@aaronstacy:是的,我测试了一下。 (上面的代码) – unutbu 2011-05-18 21:28:42

+0

请注意,如果密码大于操作系统的管道缓冲区,则存在死锁的理论危险。为了安全起见,您必须执行IO多路复用,并在启动过程后编写密码。 – 2015-08-31 17:31:16