<p><em>对Python2.6的限制后来被添加到问题中。答案的最后是一个可移植的解决方案。</em></p>
<hr/>
<p>由于python3.5,<a href="https://docs.python.org/3/library/subprocess.html#subprocess.run" rel="nofollow noreferrer">^{<cd1>}</a>应该匹配大多数“用X调用程序”用例。它的<code>input</code>参数满足您的要求:</p>
<blockquote>
<p>The <code>input</code> argument is passed to [...] the subprocess’s stdin.</p>
</blockquote>
<p>您可以直接向其输入<em>字节</em>字符串:</p>
<pre><code>import subprocess
g2p_process = subprocess.run(["./eng_GBR/g2p", "@g2pumap=./map.txt"], input=b'teststring\n')
</code></pre>
<p>这相当于您的bash调用。注意,您必须自己添加适当的换行符(<code>b"\n"</code>在末尾)。任何参数,如<code>@g2pumap=./map.txt</code>,都可以在不转义的情况下传入。你知道吗</p>
<p>如果您想要有<code>check_call</code>的异常,请在后面使用<code>g2p_process.check_returncode()</code>。你知道吗</p>
<hr/>
<p>如果您使用的是较旧的版本或需要向后兼容,那么使用裸的<code>subprocess.Popen</code>是最可移植的。下面应该处理您的用例:</p>
<pre><code>import subprocess
g2p_process = subprocess.Popen(
["./eng_GBR/g2p", "@g2pumap=./map.txt"],
stdin=subprocess.PIPE, # allow sending data via STDIN
)
g2p_process.communicate(input="teststring\n")
if g2p_process.returncode != 0:
raise RuntimeError
</code></pre>
<p>注意,如果需要,还可以捕获stdout和stderr。在对<code>Popen</code>的调用中使用<code>stdout=subprocess.PIPE</code>和/或<code>stderr=subprocess.PIPE</code>。这样做让<code>g2p_process.communicate</code>返回一个有意义的<code>(stdoutdata, stderrdata)</code>元组。你知道吗</p>
<p>请参阅<code>subprocess.Popen</code><a href="https://docs.python.org/2/library/subprocess.html#popen-objects" rel="nofollow noreferrer">method docs</a>中有关如何处理此类对象的内容。通常最好检查它的<code>returncode</code>或<code>kill</code>悬挂进程。如果您愿意,还可以复制<a href="https://github.com/python/cpython/blob/3.7/Lib/subprocess.py#L453" rel="nofollow noreferrer">^{<cd1>}</a>,因为它可以进行正确的错误处理。你知道吗</p>