mirror of https://github.com/xemu-project/xemu.git
qapi/gen.py: update write() to be more idiomatic
Make the file handling here just a tiny bit more idiomatic. (I realize this is heavily subjective.) Use exist_ok=True for os.makedirs and remove the exception, use fdopen() to wrap the file descriptor in a File-like object, and use a context manager for managing the file pointer. Signed-off-by: John Snow <jsnow@redhat.com> Reviewed-by: Eduardo Habkost <ehabkost@redhat.com> Reviewed-by: Cleber Rosa <crosa@redhat.com> Reviewed-by: Markus Armbruster <armbru@redhat.com> Message-Id: <20201009161558.107041-31-jsnow@redhat.com> Signed-off-by: Markus Armbruster <armbru@redhat.com>
This commit is contained in:
parent
0cbd5b0516
commit
cc6263c44b
scripts/qapi
|
@ -12,7 +12,6 @@
|
||||||
# See the COPYING file in the top-level directory.
|
# See the COPYING file in the top-level directory.
|
||||||
|
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
import errno
|
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
from typing import (
|
from typing import (
|
||||||
|
@ -65,21 +64,19 @@ class QAPIGen:
|
||||||
return
|
return
|
||||||
pathname = os.path.join(output_dir, self.fname)
|
pathname = os.path.join(output_dir, self.fname)
|
||||||
odir = os.path.dirname(pathname)
|
odir = os.path.dirname(pathname)
|
||||||
|
|
||||||
if odir:
|
if odir:
|
||||||
try:
|
os.makedirs(odir, exist_ok=True)
|
||||||
os.makedirs(odir)
|
|
||||||
except os.error as e:
|
# use os.open for O_CREAT to create and read a non-existant file
|
||||||
if e.errno != errno.EEXIST:
|
|
||||||
raise
|
|
||||||
fd = os.open(pathname, os.O_RDWR | os.O_CREAT, 0o666)
|
fd = os.open(pathname, os.O_RDWR | os.O_CREAT, 0o666)
|
||||||
f = open(fd, 'r+', encoding='utf-8')
|
with os.fdopen(fd, 'r+', encoding='utf-8') as fp:
|
||||||
text = self.get_content()
|
text = self.get_content()
|
||||||
oldtext = f.read(len(text) + 1)
|
oldtext = fp.read(len(text) + 1)
|
||||||
if text != oldtext:
|
if text != oldtext:
|
||||||
f.seek(0)
|
fp.seek(0)
|
||||||
f.truncate(0)
|
fp.truncate(0)
|
||||||
f.write(text)
|
fp.write(text)
|
||||||
f.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _wrap_ifcond(ifcond: List[str], before: str, after: str) -> str:
|
def _wrap_ifcond(ifcond: List[str], before: str, after: str) -> str:
|
||||||
|
|
Loading…
Reference in New Issue