Cron - [Permission Denied] 当我尝试从目录中保存和删除文件时

Chron - [Permission Denied] when I try to save & remove file from directory

问题:使用 Cron 计划时无法在目录 (/root/Notion/Image) 中保存文件

这就是我的代码试图做的事情:

  1. 检查电子邮件
  2. 下载图片附件
  3. 存储在目录中 - root/Notion/Image
  4. 检索文件路径

当我在 Google 云终端中手动 运行 时,脚本正在运行。问题是当我尝试在 Cron 上安排它时,它无法访问文件夹以在本地保存文件。

这是脚本失败需要权限时的错误:

Traceback (most recent call last):
  File "Notion/test.py", line 121, in <module>
    path = get_attachments(email.message_from_bytes(msg[0][1]))
  File "Notion/test.py", line 47, in get_attachments
    with open(filePath, 'wb') as f:
PermissionError: [Errno 13] Permission denied: '/root/Notion/Image/3.jpeg'

这是从电子邮件中检索附件的代码

    def get_attachments(msg):
        for part in msg.walk():
            if part.get_content_maintype()=='multipart':
                continue
            if part.get('Content-Disposition') is None:
                continue
    
            fileName = part.get_filename()
    
            if bool(fileName):
                filePath = os.path.join(attachment_dir, fileName)
                with open(filePath, 'wb') as f:
                    f.write(part.get_payload(decode=True))
                    return str(filePath)

已解决: 问题是我不应该使用根目录,因为它需要权限。我已将其更改为主目录。

attachment_dir = '/home/dev_thomas_yang/folder_name/folder_name'

需要查询回家方向的人,只需运行这个脚本即可。

    from pathlib import Path
    home= str(Path.home())
    
    print(home)

感谢 Triplee 耐心地解决我的问题,尽管我的表达方式很草率!

最简单的解决方法是更改​​代码,使其不会尝试写入 /root。让它写入调用用户的主目录。

您的问题没有显示代码的相关部分,只是更改 attachment_dir 所以它不是绝对路径。如果目录尚不存在,可能会单独创建目录。

import pathlib
# ...
attachment_dir = pathlib.Path("cron/whatever/attachments").mkdir(parents=True, exist_ok=True)
# ...
for loop in circumstances:
    get_attachments(something)

更好的设计是让 get_attachments 接受目录名称作为参数,这样您就可以通过调用它的代码对其进行配置。全局变量很麻烦并且会导致难以调试的问题,因为它们隐藏了对理解代码很重要的信息,并且当您尝试调试该代码并且不知道代码的哪些部分依赖于旧代码时很难更改值。