在使用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'
您是否正在使用命令行运行Python可执行文件?如果不是,请尝试使用root特权在命令行中运行。而且我认为如果不使用root特权就无法创建/var/run
,因为这会造成安全问题。例如,可以用一个具有相同名称的文件夹/文件替换现有的文件夹/文件,并使用强制替换参数。
您使用root用户运行命令python project.py或使用您的主目录