Improve call to w3m

- Use stdin instead of a temporary file (needs -T argument to w3m to avoid it
  interpreting stdin as plaintext)
- Pass check=True to subprocess.run to raise an exception if w3m fails
- Catch that exception (as well as OSError, e.g. w3m not installed or not
  executable) and show an error instead of crashing dodo
This commit is contained in:
Florian Bruhin 2024-09-12 10:19:16 +02:00
parent 503763c4d7
commit 3372160149

View File

@ -63,13 +63,16 @@ def w3m_html2text(s: str) -> str:
:param s: an HTML input string
:returns: plain text representation of the HTML
"""
(fd, file) = tempfile.mkstemp(suffix='.html')
with os.fdopen(fd, 'w') as f:
f.write(s)
p = subprocess.run(['w3m', '-O', 'utf8', '-dump', file],
stdout=subprocess.PIPE, encoding='utf8')
os.remove(file)
try:
p = subprocess.run(
["w3m", "-T", "text/html", "-O", "utf8", "-dump"],
stdout=subprocess.PIPE,
encoding="utf8",
input=s,
check=True,
)
except (OSError, subprocess.CalledProcessError) as e:
return f"dodo w3m error: {e}"
return p.stdout
def linkify(s: str) -> str: