Python中文
首页
教程
问答
标签
搜索
登录
注册
从python为C调用重定向stdout
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>这是一个来自<a href="https://stackoverflow.com/q/5081657/572616">here</a>的后续问题,特别是关于它的<a href="https://stackoverflow.com/a/5103455/572616">answer</a>。在</p> <hr/> <p>在python模块中,我调用了一个<em>helloworld</em>可执行文件,它只需将<code>Hello World</code>打印到stdout。我有兴趣将输出重定向到python <code>StringIO</code>并遇到{a3}答案,这几乎让我找到了解决方案。在</p> <p>这个答案的关键部分是以下代码段:</p> <pre><code>1. def redirect_stdout(): 2. print "Redirecting stdout" 3. sys.stdout.flush() # <--- important when redirecting to files 4. newstdout = os.dup(1) 5. devnull = os.open('/dev/null', os.O_WRONLY) 6. os.dup2(devnull, 1) 7. os.close(devnull) 8. sys.stdout = os.fdopen(newstdout, 'w') </code></pre> <p>我还想恢复stdout,因为它是在重定向之前。在</p> <h3>问题</h3> <ol> <li>上面的函数到底是怎么回事? <ul> <li><code>dup</code>和{<cd4>}在做什么?在</li> <li>什么是<code>/dev/null</code>?在</li> <li>8号线在干什么?(<code>sys.stdout = os.fdopen(newstdout, 'w')</code>)</li> </ul></li> <li>如何将stdout存储在<code>StringIO</code>对象中?在</li> <li>在调用我的<em>Hello World</em>程序后,如何恢复stdout?在</li> </ol> <p>我很肯定,一旦我有了问题1的答案,问题2和3的答案将很容易。我决定无论如何都把它们贴出来,也许可以把问题1的答案推到我想去的地方。在</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>请参见<a href="http://linux.die.net/man/2/dup" rel="nofollow">manual pages</a>,了解作为这些Python函数基础的C运行时函数。在</p> <p>基本上,它们将一个文件描述符复制到一个新的文件描述符(使用<code>dup()</code>)或使用<code>dup2()</code>复制到调用中指定的文件描述符中。在</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
文本导入时标题行中的特殊字符
10 回答
文本小部件:在没有输入时更新并在循环后保持空闲
10 回答
文本小部件tkin
4 回答
文本小部件tkinter中的标签更改或文本外观更改是否有撤消功能?
8 回答
文本小部件tkinter复制图像选项
9 回答
文本小部件上的Python Tkinter ttk滚动条未缩放
8 回答
文本小部件上的滚动条可能需要根据制表符ord显示前进行滚动
2 回答
文本小部件不显示lis中的内容
6 回答
文本小部件不显示Unicode字符
5 回答
文本小部件中写入的行间距
3 回答
文本小部件中的文本作为变量
7 回答
文本小部件中的滚动条仅显示在底部
2 回答
文本小部件中的选项卡键空间计数
1 回答
文本小部件作为Lis
7 回答
文本小部件在主框架中扩展列宽
3 回答
文本小部件未使用删除功能清除
6 回答
文本小部件滚动动画(Tkinter、Python)
6 回答
文本居中。格式正确吗?
4 回答
文本差分算法
9 回答
文本已知时音频文件中的单词索引
8 回答