def set_pid(self, pid): with open(self.pid_path,'w+') as f: os.fchmod(f.fileno(), 0666) f.write(str(pid)) f.flush() # both contexts