简体   繁体   English

Python 在终端与 IPython Notebook 中保存 PNG

[英]Python Saving PNG in Terminal vs IPython Notebook

I am writing a basic Python module which contains a function that plots some data from a Pandas DataFrame.我正在编写一个基本的 Python 模块,其中包含一个从 Pandas DataFrame 绘制一些数据的函数。 The problem is that I expect users to call this function from both the interactive shell and IPython notebooks.问题是,我希望用户从交互式shellIPython的笔记本电脑调用这个函数。 Unfortunately, our interactive shell environment does not have any valid DISPLAY options for matplotlib to use, so I want my function (or the full module) to behave slightly different depending on which environment it is loaded into.不幸的是,我们的交互式 shell 环境没有任何有效的 DISPLAY 选项供 matplotlib 使用,所以我希望我的函数(或完整模块)的行为根据它加载到的环境而略有不同。 (Eg, the default is show the plot without saving in IPython, and save the plot without showing in the shell). (例如,默认情况下不保存在 IPython 中显示绘图,并保存绘图而不显示在 shell 中)。

This question gives me a partial answer, in that I can explicitly tell users to write matplotlib.use('Agg') before they ever import my module, but surely there is a more automated backend way to handle this? 这个问题给了我一个部分的答案,因为我可以明确告诉用户在他们导入我的模块之前编写matplotlib.use('Agg') ,但肯定有更自动化的后端方法来处理这个问题?

You could try checking if you are running into the situation (empty $DISPLAY ) and default users to the Agg backend, rather than asking them to do so.您可以尝试检查您是否遇到这种情况(空$DISPLAY )并将默认用户默认到Agg后端,而不是要求他们这样做。

def configure_matplotlib():
   import os
   if 'DISPLAY' not in os.environ:
      if matplotlib.get_backend() != 'Agg':
          matplotlib.use('Agg')


import matplotlib
configure_matplotlib()
import matplotlib.pyplot as plt
...

Now matplotlib.use has no effect once pyplot has been imported, but if your users have already done so, they probably have a working configuration anyway.现在,一旦pyplot被导入, matplotlib.use就没有任何效果,但是如果您的用户已经这样做了,他们可能无论如何都有一个可以工作的配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM