Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 带有Django的matplotlib在打印时失败[Errno 2]没有这样的文件或目录_Python_Django_Matplotlib - Fatal编程技术网

Python 带有Django的matplotlib在打印时失败[Errno 2]没有这样的文件或目录

Python 带有Django的matplotlib在打印时失败[Errno 2]没有这样的文件或目录,python,django,matplotlib,Python,Django,Matplotlib,我试图通过matplotlib创建png,但我得到: [Errno 2] No such file or directory 同样的代码也适用于单元测试打印\u图呼叫已进入 # creates a canvas from figure canvas = FigureCanvasAgg(fig) filename = "directory" + os.sep + name_prefix + ".png" # saves figure to filesystem in png format can

我试图通过matplotlib创建png,但我得到:

[Errno 2] No such file or directory
同样的代码也适用于单元测试<代码>打印\u图呼叫已进入

# creates a canvas from figure
canvas = FigureCanvasAgg(fig)
filename = "directory" + os.sep + name_prefix + ".png"
# saves figure to filesystem in png format
canvas.print_figure(filename)
我认为这可能是一个权限问题,但在我看来,通过
manage.py test


谢谢

我的建议是使用完全限定的路径名。例如:您可以根据django设置确定媒体根目录,编写一段代码以确保图形的子目录存在,然后将图像保存在那里

您当前的代码似乎依赖于在“当前工作目录”中找到具有适当名称的子目录。“当前工作目录”是一个很挑剔的东西-它在测试、开发、生产方面都会有所不同

# import settings
from django.conf import settings
...
# ensure that a subdirectory with the appropriate name exists
if not os.path.exists(directory):
    os.makedirs(directory)

# save the plots
canvas = FigureCanvasAgg(fig)
filename = settings.MEDIA_ROOT + os.sep + directory  + os.sep + name_prefix + ".png"
# saves figure to filesystem in png format
canvas.print_figure(filename)
...

您将保存在的实际位置应根据您的需要确定。关键是要使用完全限定路径,并在尝试保存图像之前检查目录/子目录是否存在。

能否确认
打印文件名是否符合预期?是的,我可以确认。。完整输出是
[Errno 2]没有这样的文件或目录:“directory/arm\u compare1f3c.png”
这正是我所期望的。我安装了
matplotlib
,第一次运行代码时收到了相同的错误。我必须在django项目的根目录中
mkdir目录
,然后图像被成功生成。