小编And*_*ham的帖子

将`sys.stdout`重定向到文件或缓冲区

我在Python 3.4中工作,我有一些我不理解的行为:如果我将stdout重定向到一个文件,我能够从子进程中捕获文本.但是,当我重定向到Python文件对象时,我停止捕获该输出.我很想解释(跟随)行为.

我有:

from multiprocessing import Process

def worker():
    print('forked output')

def output():
    print('redirected')
    p = Process(target=worker)
    p.daemon = True
    p.start()
    p.join()  # wait for subprocess to terminate
    print('end')
Run Code Online (Sandbox Code Playgroud)

redirect_stdoutPython 3.4中的上下文管理器使得stdout变得容易(在这个例子中).

from contextlib import redirect_stdout
from sys import stdout
from tempfile import TemporaryFile


with TemporaryFile(mode='w+', encoding=stdout.encoding) as buf:
    with redirect_stdout(buf):
        output()  # the function defined above
    buf.seek(0)
    s = buf.read()
    print('output from TemporaryFile:')
    print(s)
Run Code Online (Sandbox Code Playgroud)

然后我可以简单地调用脚本来获得以下输出:

$ python stackoverflow.py 
output from TemporaryFile:
redirected
forked output
end
Run Code Online (Sandbox Code Playgroud)

这正是我想要的,并且工作正常.

我的困惑来自,如果我,如果我切换事实茎TemporaryFile用 …

python stdout python-3.x

7
推荐指数
1
解决办法
530
查看次数

Python,Macports和缓冲区问题

抱歉,如果发布这个是错误的地方 - 我不清楚问题是什么.

当使用运行Mac OX 10.10的Macports 2.3.3构建的Python版本时,我看到了一些非常有趣的行为.我已经完全重新安装了Macports,并在iMac和Macbook Air上复制了这个,并创建了一个新用户,以确保它不是我的环境.这种情况上周没有发生,有时在过渡时期发生了一些变化.

一切正常,直到我调用Python.

$ python
Python 3.4.3 (default, Aug 26 2015, 18:29:14) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 1+1
>>> 2
^D>>> 
Run Code Online (Sandbox Code Playgroud)

>>>输入的结果之前正在打印,而且还经过我告诉Python与控制-d退出.

此时,所有输入都不再在终端中打印(iTerm2中也是如此).如果我输入我echo 'this is ouput; input is hidden'唯一看到的是:

$ this is ouput; input is hidden
Run Code Online (Sandbox Code Playgroud)

如果我重新调用解释器,事情会更加怪异.

$ Python 3.4.3 (default, Aug 26 2015, 18:29:14) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", …
Run Code Online (Sandbox Code Playgroud)

python macos macports

7
推荐指数
1
解决办法
501
查看次数

标签 统计

python ×2

macos ×1

macports ×1

python-3.x ×1

stdout ×1