Python Forum
Having difficulty with threads and input()
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Having difficulty with threads and input()
#7
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
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 »
Reply


Messages In This Thread
RE: Having difficulty with threads and input() - by Gribouillis - Jun-05-2024, 07:01 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Difficulty in adapting duplicates-filter in script ledgreve 5 1,087 Jul-17-2023, 03:46 PM
Last Post: ledgreve
  Difficulty with installation standenman 2 1,170 May-03-2023, 06:39 PM
Last Post: snippsat
  Difficulty with installation standenman 0 795 May-02-2023, 08:33 PM
Last Post: standenman
  Difficulty in understanding transpose with a tuple of axis numbers in 3-D new_to_python 0 1,625 Feb-11-2020, 06:03 AM
Last Post: new_to_python
  Difficulty installing Pycrypto KipCarter 4 13,282 Feb-10-2020, 07:54 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020