【问题标题】:"/Library" directory permission denied on Mac - Python3Mac 上的“/Library”目录权限被拒绝 - Python3
【发布时间】:2020-12-05 23:54:11
【问题描述】:

我正在尝试创建一个程序来复制 mac 上库目录中的目录(路径:“/Library”)。我使用了shutil,它在其他目录中效果很好,但在Library目录中却没有......

我希望能够编译我的程序,所以我不能以 root 身份运行它。

这是我的代码:

import shutil

def copy(src_path, dir_path):
    try:
        shutil.copytree(src_path, dir_path)
        print("Success!")
    except:
        print("Impossible to copy the folder...")
        print("Failed!")

copy("/Users/marinnagy/Desktop/Test", "Library/Test")

我认为这是因为库目录受到保护并且需要身份验证才能进行更改。 我必须向用户发出身份验证请求吗?还是我需要使用shutil以外的其他方法?

感谢您的帮助!

【问题讨论】:

  • 你试过以root运行它吗?
  • 使用 sudo 命令?不,我没有,但我希望能够用 pyinstaller 编译程序,所以这对我来说不是一个很好的解决方案......

标签: python authentication directory copy paste


【解决方案1】:

经过大量研究和多次尝试,我终于设法将一个文件夹复制到我的库目录中。

在 macOS 上,写入受保护目录(如库目录)的过程对于 python 程序被阻止。一旦编译(我使用 pyinstaller),python 应用程序似乎不可能访问这种文件夹,即使您在系统偏好设置中为应用程序提供全盘访问权限。

所以我使用了一些 AppleScript 来管理这个特定的复制/粘贴任务:

on run {scr_path, dir_path} # Run with arguments
    # Translate standard paths to their quoted form
    set formated_scr_path to quoted form of scr_path
    set formated_dir_path to quoted form of dir_path
    # Run a simple shell script to copy the repertory in the other
    do shell script "cp -R " & formated_scr_path & space & formated_dir_path ¬
    with administrator privileges # Ask for administrator privileges
end run

然后,在我的 python 程序中,当我想复制/粘贴到受保护的库(如库库)时,我调用 AppleScript 程序:

import subprocess

def copy(scr_path, dir_path):
    # Use the osascript process to call the AppleScript
    # Give the paths in arguments
    process = subprocess.call(['osascript', "path/to/applescript", 
    scr_path, dir_path])
return process

copy("path/to/folder 1", "path/to/folder 2")

这种方法对我来说适用于受保护的曲目。 AppleScript 在后台运行并弹出一个身份验证窗口,要求用户将自己标识为管理员: result screenshot

【讨论】:

    猜你喜欢
    • 2021-09-04
    • 2014-01-22
    • 2021-06-17
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 2011-01-16
    • 2020-11-25
    相关资源
    最近更新 更多