Jun-05-2024, 07:01 AM
(This post was last modified: Jun-05-2024, 07:02 AM by Gribouillis.)
Disclaimer: does not work for what you want to do.
You can perhaps try this code where I interrupt the main thread which reads stdin by closing stdin in another thread. It works for me in Linux
You can perhaps try this code where I interrupt the main thread which reads stdin by closing stdin in another thread. It works for me in Linux
import sys import threading from time import sleep def work(): sleep(3) sys.stdin.close() print("End of worker's task!") def main(): worker = threading.Thread(target=work) worker.start() try: for line in sys.stdin: print(line, end='') except ValueError as err: print(repr(err)) finally: worker.join() if __name__ == '__main__': main()
Output:λ python paillasse/pf/inputthread.py
spam
spam
eggs
eggs
End of worker's task!
ValueError('I/O operation on closed file.')
EDIT: Unfortunately it does not work! the error is not thrown unless stdin tries to read a line after it was closed! You could as well check in the loop if an event is set.
« We can solve any problem by introducing an extra level of indirection »