Use context managers to open files

Inspired by d50a6ddc1b.
This commit is contained in:
Luflosi 2019-08-01 13:21:26 -05:00
parent 68f3b6fbeb
commit 5f855ce547
No known key found for this signature in database
GPG Key ID: 14140F703B7D8362
17 changed files with 161 additions and 139 deletions

View File

@ -107,7 +107,8 @@ features of the graphics protocol:
sys.stdout.flush() sys.stdout.flush()
cmd.clear() cmd.clear()
write_chunked({'a': 'T', 'f': 100}, open(sys.argv[-1], 'rb').read()) with open(sys.argv[-1], 'rb') as f:
write_chunked({'a': 'T', 'f': 100}, f.read())
Save this script as :file:`png.py`, then you can use it to display any PNG Save this script as :file:`png.py`, then you can use it to display any PNG

View File

@ -229,7 +229,8 @@ def script_launch():
def update_intaller_wrapper(): def update_intaller_wrapper():
# To run: python3 -c "import runpy; runpy.run_path('installer.py', run_name='update_wrapper')" installer.sh # To run: python3 -c "import runpy; runpy.run_path('installer.py', run_name='update_wrapper')" installer.sh
src = open(__file__, 'rb').read().decode('utf-8') with open(__file__, 'rb') as f:
src = f.read().decode('utf-8')
wrapper = sys.argv[-1] wrapper = sys.argv[-1]
with open(wrapper, 'r+b') as f: with open(wrapper, 'r+b') as f:
raw = f.read().decode('utf-8') raw = f.read().decode('utf-8')

View File

@ -29,10 +29,12 @@ def get_data(fname, folder='UCD'):
bn = os.path.basename(url) bn = os.path.basename(url)
local = os.path.join('/tmp', bn) local = os.path.join('/tmp', bn)
if os.path.exists(local): if os.path.exists(local):
data = open(local, 'rb').read() with open(local, 'rb') as f:
data = f.read()
else: else:
data = urlopen(url).read() data = urlopen(url).read()
open(local, 'wb').write(data) with open(local, 'wb') as f:
f.write(data)
for line in data.decode('utf-8').splitlines(): for line in data.decode('utf-8').splitlines():
line = line.strip() line = line.strip()
if line and not line.startswith('#'): if line and not line.startswith('#'):
@ -166,7 +168,7 @@ def write_case(spec, p):
@contextmanager @contextmanager
def create_header(path, include_data_types=True): def create_header(path, include_data_types=True):
f = open(path, 'w') with open(path, 'w') as f:
p = partial(print, file=f) p = partial(print, file=f)
p('// unicode data, built from the unicode standard on:', date.today()) p('// unicode data, built from the unicode standard on:', date.today())
p('// see gen-wcwidth.py') p('// see gen-wcwidth.py')
@ -180,7 +182,6 @@ def create_header(path, include_data_types=True):
p() p()
if include_data_types: if include_data_types:
p('END_ALLOW_CASE_RANGE') p('END_ALLOW_CASE_RANGE')
f.close()
def gen_emoji(): def gen_emoji():
@ -282,7 +283,9 @@ def gen_ucd():
p('combining_type mark_for_codepoint(char_type c) {') p('combining_type mark_for_codepoint(char_type c) {')
rmap = codepoint_to_mark_map(p, mark_map) rmap = codepoint_to_mark_map(p, mark_map)
p('}\n') p('}\n')
expected = int(re.search(r'^#define VS15 (\d+)', open('kitty/unicode-data.h').read(), re.M).group(1)) with open('kitty/unicode-data.h') as f:
unicode_data = f.read()
expected = int(re.search(r'^#define VS15 (\d+)', unicode_data, re.M).group(1))
if rmap[0xfe0e] != expected: if rmap[0xfe0e] != expected:
raise ValueError('The mark for 0xfe0e has changed, you have to update VS15 to {} and VS16 to {} in unicode-data.h'.format( raise ValueError('The mark for 0xfe0e has changed, you have to update VS15 to {} and VS16 to {} in unicode-data.h'.format(
rmap[0xfe0e], rmap[0xfe0f] rmap[0xfe0e], rmap[0xfe0f]

View File

@ -38,7 +38,8 @@ def init_env(env, pkg_config, at_least_version, test_compile, module='x11'):
) )
else: else:
ans.ldpaths.extend('-lrt -lm -ldl'.split()) ans.ldpaths.extend('-lrt -lm -ldl'.split())
sinfo = json.load(open(os.path.join(base, 'source-info.json'))) with open(os.path.join(base, 'source-info.json')) as f:
sinfo = json.load(f)
module_sources = list(sinfo[module]['sources']) module_sources = list(sinfo[module]['sources'])
if module in ('x11', 'wayland'): if module in ('x11', 'wayland'):
remove = 'linux_joystick.c' if is_bsd else 'null_joystick.c' remove = 'linux_joystick.c' if is_bsd else 'null_joystick.c'
@ -157,7 +158,8 @@ class Function:
def generate_wrappers(glfw_header): def generate_wrappers(glfw_header):
src = open(glfw_header).read() with open(glfw_header) as f:
src = f.read()
functions = [] functions = []
first = None first = None
for m in re.finditer(r'^GLFWAPI\s+(.+[)]);\s*$', src, flags=re.MULTILINE): for m in re.finditer(r'^GLFWAPI\s+(.+[)]);\s*$', src, flags=re.MULTILINE):

View File

@ -249,7 +249,8 @@ class ImageManager:
cmd, standard_b64encode(rgba_path.encode(fsenc))) cmd, standard_b64encode(rgba_path.encode(fsenc)))
else: else:
import zlib import zlib
data = open(rgba_path, 'rb').read() with open(rgba_path, 'rb') as f:
data = f.read()
cmd['S'] = len(data) cmd['S'] = len(data)
data = zlib.compress(data) data = zlib.compress(data)
cmd['o'] = 'z' cmd['o'] = 'z'

View File

@ -30,14 +30,16 @@ if is_macos:
else: else:
def cmdline_of_process(pid): def cmdline_of_process(pid):
return list(filter(None, open('/proc/{}/cmdline'.format(pid), 'rb').read().decode('utf-8').split('\0'))) with open('/proc/{}/cmdline'.format(pid), 'rb') as f:
return list(filter(None, f.read().decode('utf-8').split('\0')))
def cwd_of_process(pid): def cwd_of_process(pid):
ans = '/proc/{}/cwd'.format(pid) ans = '/proc/{}/cwd'.format(pid)
return os.path.realpath(ans) return os.path.realpath(ans)
def _environ_of_process(pid): def _environ_of_process(pid):
return open('/proc/{}/environ'.format(pid), 'rb').read().decode('utf-8') with open('/proc/{}/environ'.format(pid), 'rb') as f:
return f.read().decode('utf-8')
def process_group_map(): def process_group_map():
ans = defaultdict(list) ans = defaultdict(list)
@ -47,7 +49,8 @@ else:
except Exception: except Exception:
continue continue
try: try:
raw = open('/proc/' + x + '/stat', 'rb').read().decode('utf-8') with open('/proc/' + x + '/stat', 'rb') as f:
raw = f.read().decode('utf-8')
except EnvironmentError: except EnvironmentError:
continue continue
try: try:

View File

@ -728,9 +728,11 @@ def create_opts(args, debug_config=False, accumulate_bad_lines=None):
import subprocess import subprocess
print(' '.join(subprocess.check_output(['sw_vers']).decode('utf-8').splitlines()).strip()) print(' '.join(subprocess.check_output(['sw_vers']).decode('utf-8').splitlines()).strip())
if os.path.exists('/etc/issue'): if os.path.exists('/etc/issue'):
print(open('/etc/issue', encoding='utf-8', errors='replace').read().strip()) with open('/etc/issue', encoding='utf-8', errors='replace') as f:
print(f.read().strip())
if os.path.exists('/etc/lsb-release'): if os.path.exists('/etc/lsb-release'):
print(open('/etc/lsb-release', encoding='utf-8', errors='replace').read().strip()) with open('/etc/lsb-release', encoding='utf-8', errors='replace') as f:
print(f.read().strip())
config = tuple(x for x in config if os.path.exists(x)) config = tuple(x for x in config if os.path.exists(x))
if config: if config:
print(green('Loaded config files:'), ', '.join(config)) print(green('Loaded config files:'), ', '.join(config))

View File

@ -157,7 +157,8 @@ def replay(raw):
def main(path): def main(path):
raw = open(path).read() with open(path) as f:
raw = f.read()
replay(raw) replay(raw)
with suppress(EOFError, KeyboardInterrupt): with suppress(EOFError, KeyboardInterrupt):
input() input()

View File

@ -177,11 +177,10 @@ def load_config(Options, defaults, parse_config, merge_configs, *paths, override
if not path: if not path:
continue continue
try: try:
f = open(path, encoding='utf-8', errors='replace') with open(path, encoding='utf-8', errors='replace') as f:
vals = parse_config(f)
except FileNotFoundError: except FileNotFoundError:
continue continue
with f:
vals = parse_config(f)
ans = merge_configs(ans, vals) ans = merge_configs(ans, vals)
if overrides is not None: if overrides is not None:
vals = parse_config(overrides) vals = parse_config(overrides)

View File

@ -293,7 +293,7 @@ def generate_key_table():
# To run this, use: python3 . +runpy "from kitty.keys import *; generate_key_table()" # To run this, use: python3 . +runpy "from kitty.keys import *; generate_key_table()"
import os import os
from functools import partial from functools import partial
f = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys.h'), 'w') with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys.h'), 'w') as f:
w = partial(print, file=f) w = partial(print, file=f)
w('// auto-generated from keys.py, do not edit!') w('// auto-generated from keys.py, do not edit!')
w('#pragma once') w('#pragma once')

3
kitty/rgb.py generated
View File

@ -835,7 +835,8 @@ if __name__ == '__main__':
import sys import sys
import pprint import pprint
data = {} data = {}
for line in open(sys.argv[-1]): with open(sys.argv[-1]) as f:
for line in f:
line = line.strip() line = line.strip()
if not line or line.startswith('!'): if not line or line.startswith('!'):
continue continue

View File

@ -23,8 +23,10 @@ BASE = os.path.dirname(os.path.abspath(__file__))
def load_shaders(name): def load_shaders(name):
from .fast_data_types import GLSL_VERSION from .fast_data_types import GLSL_VERSION
vert = open(os.path.join(BASE, '{}_vertex.glsl'.format(name))).read().replace('GLSL_VERSION', str(GLSL_VERSION), 1) with open(os.path.join(BASE, '{}_vertex.glsl'.format(name))) as f:
frag = open(os.path.join(BASE, '{}_fragment.glsl'.format(name))).read().replace('GLSL_VERSION', str(GLSL_VERSION), 1) vert = f.read().replace('GLSL_VERSION', str(GLSL_VERSION), 1)
with open(os.path.join(BASE, '{}_fragment.glsl'.format(name))) as f:
frag = f.read().replace('GLSL_VERSION', str(GLSL_VERSION), 1)
return vert, frag return vert, frag

View File

@ -56,7 +56,8 @@ def main():
raise SystemExit('Must specify a PNG file to display') raise SystemExit('Must specify a PNG file to display')
clear_screen() clear_screen()
display(b'\xdd\xdd\xdd\xff', 1, 1, 0, 0, -10, 40, 20) display(b'\xdd\xdd\xdd\xff', 1, 1, 0, 0, -10, 40, 20)
display(open(os.path.join(base, '../logo/kitty.rgba'), 'rb').read(), 256, 256, 0, 5, -9) with open(os.path.join(base, '../logo/kitty.rgba'), 'rb') as f:
display(f.read(), 256, 256, 0, 5, -9)
display(b'\0\0\0\xaa', 1, 1, 0, 7, -8, 40, 3) display(b'\0\0\0\xaa', 1, 1, 0, 7, -8, 40, 3)
move_cursor(5, 8) move_cursor(5, 8)
print('kitty is \033[3m\033[32mawesome\033[m!') print('kitty is \033[3m\033[32mawesome\033[m!')

View File

@ -23,7 +23,8 @@ os.chdir(os.path.dirname(os.path.abspath(__file__)))
build_path = os.path.abspath('../build-kitty') build_path = os.path.abspath('../build-kitty')
docs_dir = os.path.abspath('docs') docs_dir = os.path.abspath('docs')
publish_dir = os.path.abspath(os.path.join('..', 'kovidgoyal.github.io', 'kitty')) publish_dir = os.path.abspath(os.path.join('..', 'kovidgoyal.github.io', 'kitty'))
raw = open('kitty/constants.py').read() with open('kitty/constants.py') as f:
raw = f.read()
nv = re.search( nv = re.search(
r'^version\s+=\s+\((\d+), (\d+), (\d+)\)', raw, flags=re.MULTILINE) r'^version\s+=\s+\((\d+), (\d+), (\d+)\)', raw, flags=re.MULTILINE)
version = '%s.%s.%s' % (nv.group(1), nv.group(2), nv.group(3)) version = '%s.%s.%s' % (nv.group(1), nv.group(2), nv.group(3))

View File

@ -315,7 +315,8 @@ def get_vcs_rev_defines():
with open('.git/refs/heads/master') as f: with open('.git/refs/heads/master') as f:
rev = f.read() rev = f.read()
except NotADirectoryError: except NotADirectoryError:
gitloc = open('.git').read() with open('.git') as f:
gitloc = f.read()
with open(os.path.join(gitloc, 'refs/heads/master')) as f: with open(os.path.join(gitloc, 'refs/heads/master')) as f:
rev = f.read() rev = f.read()
@ -343,7 +344,8 @@ def newer(dest, *sources):
def dependecies_for(src, obj, all_headers): def dependecies_for(src, obj, all_headers):
dep_file = obj.rpartition('.')[0] + '.d' dep_file = obj.rpartition('.')[0] + '.d'
try: try:
deps = open(dep_file).read() with open(dep_file) as f:
deps = f.read()
except FileNotFoundError: except FileNotFoundError:
yield src yield src
yield from iter(all_headers) yield from iter(all_headers)

View File

@ -46,7 +46,8 @@ def run(what):
raise SystemExit(ret.returncode) raise SystemExit(ret.returncode)
script = open(__file__, 'rb').read().decode('utf-8') with open(__file__, 'rb') as f:
script = f.read().decode('utf-8')
script = script[:script.find('# EOF_REMOTE')].replace('if False:', 'if True:', 1) script = script[:script.find('# EOF_REMOTE')].replace('if False:', 'if True:', 1)
os.chdir(os.path.expanduser('~/work/build-kitty')) os.chdir(os.path.expanduser('~/work/build-kitty'))
with tempfile.NamedTemporaryFile(prefix='install-dmg-', suffix='.py') as f: with tempfile.NamedTemporaryFile(prefix='install-dmg-', suffix='.py') as f:

View File

@ -44,7 +44,8 @@ def run(what):
raise SystemExit(ret.returncode) raise SystemExit(ret.returncode)
script = open(__file__, 'rb').read().decode('utf-8') with open(__file__, 'rb') as f:
script = f.read().decode('utf-8')
script = script[:script.find('# EOF_REMOTE')].replace('if False:', 'if True:', 1) script = script[:script.find('# EOF_REMOTE')].replace('if False:', 'if True:', 1)
os.chdir(os.path.expanduser('~/work/build-kitty')) os.chdir(os.path.expanduser('~/work/build-kitty'))
with tempfile.NamedTemporaryFile(prefix='install-tarball-', suffix='.py') as f: with tempfile.NamedTemporaryFile(prefix='install-tarball-', suffix='.py') as f: