我想在python中使用这个库来生成电气图: https://cdelker.bitbucket.io/SchemDraw/ , 我想在服务器中运行这段代码。
想法是生成图像,将其保存在服务器中,然后通过 url 将其提供给客户端。
我正在使用它的示例代码来测试:
import SchemDraw as schem
import SchemDraw.elements as e
d = schem.Drawing()
V1 = d.add(e.SOURCE_V, label='10V')
d.add(e.RES, d='right', label='100K$\Omega$')
d.add(e.CAP, d='down', botlabel='0.1$\mu$F')
d.add(e.LINE, to=V1.start)
d.add(e.GND)
d.draw()
d.save('testschematic.svg')
它工作正常,但问题是图像出现,我需要手动保存它,如果我在服务器中执行这段代码,它会给我错误:
File "/usr/local/lib/python3.5/tkinter/init.py", line 1877, in init api_1 | self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) api_1 | _tkinter.TclError: no display name and no $DISPLAY environment variable
我猜想在服务器中显示图像是不可能的,因为它没有可视化界面。
是否可以在不显示的情况下保存它?
最佳答案
官方文档现在有一个部分:https://schemdraw.readthedocs.io/en/latest/usage/start.html#server-side
截至schemdraw
0.8,可以保存图片bytes
直接访问内存中的变量,而不需要弹出文件或窗口。
from schemdraw import Drawing, ImageFormat
import matplotlib
matplotlib.use('Agg') # Set the backend here
drawing = Drawing()
# Add circuit components here.
# Save the schematic bytes to a variable.
image_bytes = drawing.get_imagedata(ImageFormat.SVG)
对于 schemdraw <= 0.7.1
:
SchemDraw 的作者 Collin Delker 在 https://www.collindelker.com/2014/08/29/electrical-schematic-drawing-python.html 上提供了这个建议。使用 matplotlib.use
更改 matplotlib 后端.
SchemDraw 在 Matplotlib 图形上绘制,因此如果您有交互式 Matplotlib 后端,它将尝试在窗口中显示图像,这在服务器上是不可能的。首先尝试将后端设置为其他内容,例如“Agg”,然后看看是否能解决问题:
import matplotlib
matplotlib.use('Agg') # Set the backend here
import SchemDraw as schem
import SchemDraw.elements as e
d = schem.Drawing()
...
d.draw()
d.save('mycircuit.svg')
它对我有用。
关于python - 使用 SchemDraw 库自动保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49158923/