实时捕获函数的输出 [英] Capture the output from function in real time python
问题描述
我没有找到我想要的东西。
I didn't find quite what I was looking for.
我想实时获取python函数的输出(stdout)。
I want to obtain the output (stdout) from a python function in real time.
实际的问题是我想在UI中绘制带有进度条的图形(使用来自sympy的cplot)。参数 verbose
使cplot将进度输出到stdout。
The actual problem is that I want to plot a graph (with cplot from sympy) with a progress bar in my UI. The argument verbose
makes cplot output the progress to stdout.
sympy.mpmath.cplot(lambda z: z, real, imag, verbose=True)
输出为像这样的东西:
0 of 71
1 of 71
2 of 71
...
以此类推。
I想逐行捕获,以便可以制作进度条。 (我意识到,如果不实现多线程,这可能是不可能的)。我正在使用python2.7(主要是因为我需要python3中没有的库)
I want to capture line by line so I can make a progress bar. (I realize this might not be possible without implementing multithreading). I'm using python2.7 (mainly because I need libraries that aren't in python3)
所以,¿我如何实现?
推荐答案
另一种可能性是猴子补丁 sympy.mpmath.visualization.print
,因为 cplot
使用 print
打印输出,并使用__future__ import print_function >。
Another possibility would be to monkeypatch sympy.mpmath.visualization.print
, since cplot
uses print
to print the output, and it uses from __future__ import print_function
.
首先,如果您未使用Python 3,请确保使用__future__ import print_function 中的否则将是SyntaxError。
First, make sure you are using from __future__ import print_function
if you aren't using Python 3, as this will otherwise be a SyntaxError.
然后类似
def progressbar_print(*args, **kwargs):
# Take *args and convert it to a progress output
progress(*args)
# If you want to still print the output, do it here
print(*args, **kwargs)
sympy.mpmath.visualization.print = progressbar_print
您可能想在一个自定义函数中对其进行猴子修补,使其放回原处,因为该模块中的其他函数也可能会使用 print
。同样,请记住使用上下文管理器或 finally
块执行此操作,以便即使引发异常也可以将其放回原处。
You might want to monkeypatch it in a custom function that puts it back, as other functions in that module might use print
as well. Again, remember to do this using either a context manager or a finally
block so that it gets put back even if an exception is raised.
Monkeypatching sys.stdout
绝对是更标准的方法,但是我喜欢这种解决方案表明具有 print
作为函数实际上是有用的。
Monkeypatching sys.stdout
is definitely the more standard way of doing this, but I like this solution in that it shows that having print
as a function can actually be useful.
这篇关于实时捕获函数的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!