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

标签 python linux file pid

在使用 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 授予读/写文件的完全权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59587143/

相关文章:

python - 写入命令不会在同一行上打印所有内容

Python Numpy.matrix 乘法错误

linux - 解密失败: No secret key using GPG

python将多行中的单词提取到1个列表中

linux - LeakSanitizer 无法在 Ubuntu 18.04 的 gdb 下工作?

c++ - 如果文件/目录大小增加到配置级别以上,有没有办法在 linux 中回调

java - 无法使用 Java 中的 Scanner 比较从 txt 文件读取的行

c++ - '�' 而不是文件中的普通文本

python - 使用 R SOAP (SSOAP) 检索数据/抓取

python - 将字符串转换为字典列表 Python3