擅长:python、mysql、java
<p>我知道这个问题已经过时了,但有一部分问题还没有得到回答:</p>
<blockquote>
<p>"How to catch output of commands that don't directly write to the stdout of Python, like: 1+1 ?"</p>
</blockquote>
<p>以下是步骤(对于Python3.4):</p>
<ol>
<li><p>使用Mark的解决方案将stdout/stderr重定向到Python变量:<a href="https://stackoverflow.com/a/4307737/1046299">https://stackoverflow.com/a/4307737/1046299</a></p></li>
<li><p>从Python源代码复制函数<code>PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)</code>。它位于文件<code>pythonrun.c</code></p></li>
<li><p>修改<code>PyRun_InteractiveOneObject</code>函数名和签名,以便新函数将<code>const char*</code>(您的命令)作为第一个参数,而不是<code>FILE*</code>。然后需要在函数实现中使用<code>PyParser_ASTFromStringObject</code>,而不是<code>PyParser_ASTFromFileObject</code>。注意,您需要从Python中复制函数<code>run_mod</code><em>,因为它是在函数中调用的。</p></li>
<li><p>使用命令调用新函数,例如<code>1+1</code>。Stdout现在应该接收输出<code>2</code>。</p></li>
</ol>