在使用 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/