<p>克里斯:
因为你有一个简单的例子os.管道感谢Lars,我将提供<a href="https://github.com/ryran/pyrite/" rel="nofollow">Pyrite</a>(我的gpg的GTK前端)的功能,希望更多的代码示例更好。由于gui方面的原因,我的用例比你的要复杂一点,因为我实际上使用了一个字典来输入和输出,并且我有代码以stdin作为输入来启动gpg,以及用文件作为输入启动gpg的代码,以及其他一些复杂的情况。在</p>
<p>警告说,我和您一样从列表中的gpg命令行开始;但是,我没有使用<code> passphrase-fd 0</code>,而是通过<code>os.pipe()</code>创建一个自定义文件描述符,在加载<code>Popen()</code>实例之前发送密码,该实例的输入数据为<code>stdin=subprocess.PIPE</code>。以下是黄铁矿<a href="https://github.com/ryran/pyrite/blob/master/modules/crypt_interface.py" rel="nofollow">crypt_interface</a>模块的相关(修改)摘录。在</p>
<pre><code>#!/usr/bin/env python
# Adapted excerpts from Pyrite <http://github.com/ryran/pyrite>
from subprocess import Popen, PIPE, check_output
...
# I/O dictionary obj
self.io = dict(
stdin='', # Stores input text for subprocess
stdout='', # Stores stdout stream from subprocess
stderr=0, # Stores tuple of r/w file descriptors for stderr stream
gstatus=0, # Stores tuple of r/w file descriptors for gpg-status stream
infile=0, # Input filename for subprocess
outfile=0) # Output filename for subprocess
...
cmd = ['gpg']
fd_pwd_R, fd_pwd_W = os.pipe()
os.write(fd_pwd_W, passwd)
os.close(fd_pwd_W)
cmd.append(' passphrase-fd')
cmd.append(str(fd_pwd_R))
...
# If working direct with files, setup our Popen instance with no stdin
if self.io['infile']:
self.childprocess = Popen(cmd, stdout=PIPE, stderr=self.io['stderr'][3])
# Otherwise, only difference for Popen is we need the stdin pipe
else:
self.childprocess = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=self.io['stderr'][4])
# Time to communicate! Save output for later
self.io['stdout'] = self.childprocess.communicate(input=self.io['stdin'])[0]
# Clear stdin from our dictionary asap, in case it's huge
self.io['stdin'] = ''
# Close os file descriptors
if fd_pwd_R:
os.close(fd_pwd_R)
time.sleep(0.1) # Sleep a bit to ensure everything gets read
os.close(self.io['stderr'][5])
if self.io['gstatus']:
os.close(self.io['gstatus'][6])
...
</code></pre>
<p>调用所有等待的函数,直到<code>self.childprocess</code>对象具有<code>returncode</code>属性,并假定返回代码是<code>0</code>,并且输入是文本(而不是文件),然后从字典中读取gpg的stdout并将其打印到屏幕上。在</p>
<p>乐于回答问题或尝试从我有限的经验中提供帮助。可以通过以下链接找到我的联系方式。在</p>
<p>编辑:您可能还发现<a href="https://github.com/ryran/b19scripts/blob/master/a4crypt.py" rel="nofollow">a4crypt</a>很有启发性,因为它是gpg的一个更简单的前端,它是我为了学习python而开始的项目,后来在我“完成”(如果有这样的事情的话)黄铁矿之后被封存。在</p>