Skip to content

Instantly share code, notes, and snippets.

@user202729
Last active September 30, 2025 08:35
Show Gist options
  • Select an option

  • Save user202729/d1c0435b79faa94faee610a244a3610d to your computer and use it in GitHub Desktop.

Select an option

Save user202729/d1c0435b79faa94faee610a244a3610d to your computer and use it in GitHub Desktop.
watching-mupdf script: Wrapper around mupdf to allow automatically refreshing on file change, see also https://unix.stackexchange.com/questions/425907/how-to-make-mupdf-automatically-refresh-a-document
#!/bin/python3
from pathlib import Path
import sys
import argparse
parser=argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("filename", type=Path)
args=parser.parse_args()
if not args.filename.is_file():
raise FileNotFoundError("File does not exist")
import subprocess
import os
import threading
import typing
import time
mupdf_process=subprocess.Popen(["mupdf", args.filename])
def kill_mupdf():
mupdf_process.wait()
subprocess.run(["kill", "-INT", str(os.getpid())]) # whole program, use INT to allow cleanup
threading.Thread(target=kill_mupdf).start()
use_when_changed = subprocess.run(["which", "when-changed"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL).returncode == 0
if use_when_changed:
subprocess.run([
"when-changed", "-1", args.filename, "-c",
"bash", "-c", "echo File changed.; sleep 0.2s; kill -HUP "+str(mupdf_process.pid)], check=True)
else:
while True:
subprocess.run(["inotifywait", "-e", "close_write", args.filename], check=True)
print("File changed.")
subprocess.run(["kill", "-HUP", str(mupdf_process.pid)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment