2011-05-18 90 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