I am a beginner in python and this question may seem redundant but I have not been able to solve this. I want to run a function that takes a user input and keeps waiting for user input in background while main function keeps running.
The function takes parameters as arguments that are dependent on the main function. Also, if the user doesn't give any input, then the code below that function must execute.
I have been trying to use threading concept but found no success. The code is as follows:
import sys
import time
import logging
import threading
event_handler = Handler()
observer = watchdog.observers.Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
import watchdog.events
import watchdog.observers
import queue
import itertools
from copy import deepcopy
class Handler(watchdog.events.PatternMatchingEventHandler):
def __init__(self):
watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=['*.txt'],
ignore_directories=True, case_sensitive=False)
def function_to_be_threaded(self,user_input,arg1,arg2,val):
user_input[0] = input('Enter information')
...
...
val[0] = ...
def on_created(self,):
...
...
arg1 = ...
arg2 = ...
user_input = [None]
val = [None]
flag = False
t = threading.Thread(target = function_to_be_threaded, args = (user_input,arg1,arg2,val,))
t.daemon = True
t.start()
for i in range(1,10):
time.sleep(1)
if(user_input[0] is not None):
result = val[0]
...
flag = True
break
if(not flag):
...
...
... #this part should always execute irrespective of flag
...
But the code keeps waiting for user input and crashes after some time.