When reading from a pipe in Python, especially in a one-liner like your example, the script may hang because the pipe remains open even after your script exits. This happens because inotifywait keeps the write end of the pipe open, and Python's stdin (the read end) is still being monitored.
break and exit(0) don't workbreak only exits a loop, but the script continues running.exit(0) exits the script, but the pipe may still be held open by the shell or inotifywait.In your Python one-liner, explicitly close sys.stdin after reading. This signals to the pipe that the reader is done.
bashinotifywait --monitor --event CLOSE_NOWRITE . | python3 -c 'import sys; print(sys.stdin.read()); sys.stdin.close()'
sys.exit() after closing stdinIf you want to exit immediately after reading, combine sys.stdin.close() with sys.exit().
bashinotifywait --monitor --event CLOSE_NOWRITE . | python3 -c 'import sys; print(sys.stdin.read()); sys.stdin.close(); sys.exit(0)'
If you want to process lines as they come and exit when the pipe closes:
bashinotifywait --monitor --event CLOSE_NOWRITE . | python3 -c 'import sys; [print(line, end="") for line in sys.stdin]; sys.stdin.close()'
If you want to process input until the pipe is closed:
bashinotifywait --monitor --event CLOSE_NOWRITE . | python3 -c ' import sys for line in sys.stdin: print(line, end="") if not line: # Break on empty line (optional) break sys.stdin.close() '
os._exit(0) (last resort)If the script still hangs, use os._exit(0) to forcefully exit without cleanup (not recommended unless necessary):
bashinotifywait --monitor --event CLOSE_NOWRITE . | python3 -c 'import sys, os; print(sys.stdin.read()); os._exit(0)'
sys.stdin sends an EOF signal to the pipe, allowing inotifywait to detect that the reader is done.inotifywait will then exit gracefully, and the pipe will close.