在使用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特权在命令行中运行。而且我认为不使用root特权就不可能创建/var/run,因为这会造成安全问题。例如,可以用具有相同名称的带有强制替换参数的文件夹/文件替换现有文件夹/文件。

关于python - Python授予读取/写入文件的完整权限,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59587143/

10-11 02:42
查看更多