python 3+的缓冲功能 [英] Buffer function for python 3+

查看:68
本文介绍了python 3+的缓冲功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用vtk_show打开一个vtk窗口,但是每次我这样做时,我的Ipython控制台都会崩溃,这显然是因为Ipython无法显示外部窗口,而这正是vtk_show的作用.我在Google上搜索了一个解决方案,但它是为python2编写的(我正在使用python 3.6.3).这是我找到的解决方案:

I'm trying to open a vtk window using vtk_show, but my Ipython console crashes every time i do this, apparently this is because Ipython can't display an external window, which is exactly what vtk_show does. I searched on google for a solution, but it's written for python2 (i'm using python 3.6.3). Here's the solution i found:

import vtk
from IPython.display import Image

def vtk_show(renderer, width=400, height=300):
    """
    Takes vtkRenderer instance and returns an IPython Image with the 
    rendering.
    """
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetOffScreenRendering(1)
    renderWindow.AddRenderer(renderer)
    renderWindow.SetSize(width, height)
    renderWindow.Render()

    windowToImageFilter = vtk.vtkWindowToImageFilter()
    windowToImageFilter.SetInput(renderWindow)
    windowToImageFilter.Update()

    writer = vtk.vtkPNGWriter()
    writer.SetWriteToMemory(1)
    writer.SetInputConnection(windowToImageFilter.GetOutputPort())
    writer.Write()
    data = str(buffer(writer.GetResult()))

    return Image(data)

尝试使用python2的 buffer 内置函数时遇到错误,但是由于此函数在python3 +上不存在,所以我陷入了困境.对此,我将不胜感激.预先感谢!

I'm getting an error while trying to use the buffer built-in function of python2, but as this function doesn't exist on python3+ i'm stuck.. If anyone could help me with this i would be very appreciated. Thanks in advance!

推荐答案

至少必须对代码中的这两点进行修改,以使它们与Python 3具有相同的行为:

At least these two points must be modified on your code to have the same behavior with Python 3:

  • The buffer(...) built-in function in Python 2 has been replaced by memoryview(...) in Python 3: What is Python buffer type for?. Replace the buffer call by memoryview
  • the str(...) built-in function has to replaced by a bytes(...) call to get a bytes object: https://docs.python.org/2/howto/pyporting.html#text-versus-binary-data

因此 data = ... 行应显示为:

data = bytes(memoryview(writer.GetResult()))

这篇关于python 3+的缓冲功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆