mirror of
https://github.com/kovidgoyal/kitty
synced 2026-07-17 05:54:59 +02:00
Use "with suppress()" to suppress python exceptions
Using
```Python
with suppress(OSError):
os.remove('somefile.tmp')
```
instead of
```Python
try:
os.remove('somefile.tmp')
except OSError:
pass
```
makes the code more compact and more readable IMO.
This pattern was recommended by Raymond Hettinger, a Python Core
Developer in his talk "Transforming Code into Beautiful, Idiomatic Python" at https://www.youtube.com/watch?v=OSGv2VnC0go. The transcript is available at https://github.com/JeffPaine/beautiful_idiomatic_python
This commit is contained in:
@@ -6,6 +6,7 @@ import fcntl
|
||||
import os
|
||||
from collections import defaultdict
|
||||
from contextlib import contextmanager
|
||||
from contextlib import suppress
|
||||
|
||||
import kitty.fast_data_types as fast_data_types
|
||||
|
||||
@@ -220,14 +221,10 @@ class Child:
|
||||
|
||||
def process_desc(pid):
|
||||
ans = {'pid': pid}
|
||||
try:
|
||||
with suppress(Exception):
|
||||
ans['cmdline'] = cmdline_of_process(pid)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
with suppress(Exception):
|
||||
ans['cwd'] = cwd_of_process(pid) or None
|
||||
except Exception:
|
||||
pass
|
||||
return ans
|
||||
|
||||
return list(map(process_desc, foreground_processes))
|
||||
@@ -250,25 +247,19 @@ class Child:
|
||||
|
||||
@property
|
||||
def current_cwd(self):
|
||||
try:
|
||||
with suppress(Exception):
|
||||
return cwd_of_process(self.pid)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@property
|
||||
def pid_for_cwd(self):
|
||||
try:
|
||||
with suppress(Exception):
|
||||
pgrp = os.tcgetpgrp(self.child_fd)
|
||||
foreground_processes = processes_in_group(pgrp) if pgrp >= 0 else []
|
||||
if len(foreground_processes) == 1:
|
||||
return foreground_processes[0]
|
||||
except Exception:
|
||||
pass
|
||||
return self.pid
|
||||
|
||||
@property
|
||||
def foreground_cwd(self):
|
||||
try:
|
||||
with suppress(Exception):
|
||||
return cwd_of_process(self.pid_for_cwd) or None
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
Reference in New Issue
Block a user