繁体   English   中英

Python 授予读/写文件的完全权限

[英]Python give full permissions to read/write a file

在使用 Python(3.8.0) 时,我试图在 /var/run 目录中创建一个 PID 文件。 进入时,我需要创建文件,在退出时,我需要删除文件。

class PIDFile(object):
    def __init__(self, filename='pidfileCreated.pid'):
        self._file = os.path.join("/var/run", filename)

    def __enter__(self):

        with open(self._file, "w") as f:
            f.write(str(os.getpid()))
            f.close()
            os.chmod(self._file, 0o777)

        return self

    def __exit__(self, *args):
        if os.path.exists(self._file):
            try:
                os.remove(self._file)
            except OSError:
                pass

但我得到了错误 -

with open(self._file, "w") as f:
PermissionError: [Errno 13] Permission denied: '/var/run/pidfileCreated.pid'

您是否使用命令行运行 Python 可执行文件? 如果不是,请尝试使用 root 权限使用命令行运行。 而且我认为/var/run不使用 root 权限的情况下创建/var/run不可能的,因为它会产生安全问题。 例如,可以使用强制替换参数将现有文件夹/文件替换为具有相同名称的文件夹/文件。

暂无
暂无

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

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