简体   繁体   English

使用Python Launcher保存图像而不是IDLE时的权限ERRNO13-Python

[英]Permission ERRNO13 when saving image with Python Launcher, not IDLE — Python

I have a turtle program that creates an image. 我有一个创建图像的乌龟程序。 I have the following code to save the canvas as svg. 我有以下代码将画布另存为svg。 (I don't include the turtle program here). (我这里不包括海龟程序)。

import os
import tempfile
import shutil

name = input("What would you like to name it? \n")
nameSav = name + ".png"
tmpdir = tempfile.mkdtemp()                   # create a temporary directory
tmpfile = os.path.join(tempdir, 'tmp.svg')    # name of file to save SVG to
ts = turtle.getscreen().getcanvas()
canvasvg.saveall(tmpfile, ts)
with open(tmpfile) as svg_input, open(nameSav, 'wb') as png_output:
    cairosvg.svg2png(bytestring=svg_input.read(), write_to=png_output)
shutil.rmtree(tmpdir)     # clean up temp file(s)

This works in IDLE. 这在IDLE中有效。 The canvas is saved as a png just fine. 画布可以另存为png。 If I run it with the Python Launcher for Windows, I get: 如果使用Windows的Python Launcher运行它,则会得到:

     with open(tmpfile) as svg_input, open(nameSav, 'wb') as png_output:
PermissionError: [Errno 13] Permission denied: 'test.png'

test.png is the name I chose at this point when I saved (ie, NameSav). test.png是我保存时选择的名称(即NameSav)。 So what's up with this? 那么这是怎么回事? Why doesn't IDLE get this error? 为什么IDLE没有收到此错误? How can I fix it? 我该如何解决?

The error means that permission is denied in saving test.png in the current working directory of the Python launcher, which would be the location of the launcher exe. 该错误表示在将test.png保存在Python启动器的当前工作目录中 (该文件是启动器exe的位置)时,权限被拒绝。 Give the input prompt a full path, like C:\\Users\\Spam\\Documents\\test.png , or use os.path.join to prepend an appropriate directory in front of nameSav . 为输入提示提供完整路径,例如C:\\Users\\Spam\\Documents\\test.png ,或使用os.path.joinnameSav前面添加适当的目录。

Why IDLE works is that IDLE has a different current working directory, that pointing to a folder where writes are allowed. IDLE工作的原因是IDLE具有不同的当前工作目录,该目录指向允许写入的文件夹。

Say, you want to save the resulting image to the images subfolder of the folder containing your script, you can calculate the target file name as 假设您要将结果图像保存到包含脚本的文件夹的images子文件夹中,则可以将目标文件名计算为

from os import path

filename = input("What would you like to name it? \n")
if not filename.lower().endswith('.png'):
    filename += '.png'

target_path = path.join(path.abspath(path.dirname(__file__)), 'images', filename)

with ... open(target_path, 'wb') as png_output:
    ...

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

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