如何在在线 Python 环境中更改权限或调用命令而无需更改权限?

How to change permissions or call a command without having to change permissions in an ONLINE Python environment?

我试图让我的机器人在机器人的目录中创建一个目录来存储服务器数据。

我本来只是想创建目录而不用担心权限:

@client.event
async def on_guild_join(guild):
    print(f'Recognized that Beatboxer has joined {guild.name}')
    guild_path = rf'/guilds/{guild.id}'
    if not os.path.exists(guild_path):
        os.makedirs(rf'/guilds/{guild.id}')

出现如下所示的错误消息:

Ignoring exception in on_guild_join
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 227, in on_guild_join
    os.makedirs(rf'guilds/{guild.id}')
  File "/usr/lib/python3.8/os.py", line 223, in makedirs
    mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: 'guilds/727168023101964298'

然后我尝试将 os.chmod 添加到代码中,但由于某种原因,仍然有相同的错误消息。

os.chmod("guilds", 777)
@client.event
async def on_guild_join(guild):
    print(f'Recognized that Beatboxer has joined {guild.name}')
    guild_path = rf'/guilds/{guild.id}'
    if not os.path.exists(guild_path):
        os.makedirs(rf'/guilds/{guild.id}')

此外,调用 os.chdir 并将目录更改到那里也没有用,并且出现了类似的错误消息。

os.chmod("guilds", 777)

@client.event
async def on_guild_join(guild):
    print(f'Recognized that Beatboxer has joined {guild.name}')
    guild_path = rf'/guilds/{guild.id}'
    if not os.path.exists(guild_path):
        os.chdir('/guilds')
        os.makedirs(rf'{guild.id}')

最后,我尝试了最后一件事(显然仍然没有用),即 os.popen,它为命令打开一个管道,允许它将输出传输到一个可编辑的文件由其他程序(因此不应考虑任何权限的作用):

@client.event
async def on_guild_join(guild):
    print(f'Recognized that Beatboxer has joined {guild.name}')
    guild_path = rf'/guilds/{guild.id}'
    if not os.path.exists(guild_path):
        os.popen(os.makedirs(rf'/guilds/{guild.id}'))

所有这些尝试的代码都有非常相似的错误消息,尤其是 Errno 13。计算机配置很可能无法正常工作。请帮忙?谢谢!

问题不在于你使用的函数有误

您实际上提供了一个您无权访问的目录位置。

有两种文件夹路径。绝对路径和相对路径。在您提供的示例中,您使用了绝对路径。当您使用绝对路径时,您使用根目录作为起点。在线 IDE 的问题是您通常无法直接访问根目录。因此创建新目录会出现权限错误。

那么我们该如何解决这个问题呢?我建议改用相对路径。要在您的代码中解决此问题非常容易,而不是这样做:

'/path/to/folder'

这样做:

'./path/to/folder'

通过使用 ./ 而不是 /。您使用当前文件夹而不是根目录作为起点。由于您经常可以访问当前文件夹,因此不会出现权限错误。