【问题标题】:Python give full permissions to read/write a filePython 授予读/写文件的完全权限
【发布时间】:2020-01-04 01:19:14
【问题描述】:

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

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'

【问题讨论】:

  • 一般情况下,只有root才能创建/删除/var/run中的文件。您是在寻找一种方法来规避这种情况吗?为什么?
  • 我需要为我的服务创建/访问/删除 PID 文件,该文件由这个 Python 脚本执行。存储 PID 文件的建议位置是“/var/run”文件夹。否则请提出建议。
  • 您可以选择 /var/run 的子文件夹而不是直接在其中吗?
  • 我认为有一个子文件夹不会有问题。但是当我在上面的代码中使用“/var/run/tmp”时,我得到错误“没有这样的文件或目录:'/var/run/tmp/pidfileCreated.pid'”
  • 那是因为你需要先将/var/run/tmp设为root。

标签: python linux file pid


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-28
    • 2011-12-14
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多