【发布时间】: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。