Problems with time.sleep and multithreading in Python

I have a problem with the time.sleep () function in python. I am running a script that must wait for another program to generate txt files. Although, this is a terribly old machine, so when I sleep a python script, I have problems with another program that does not create files. Are there any alternatives to using time.sleep ()? I thought blocking a thread might work, but essentially it's just a thread blocking cycle for a couple of seconds. Here I will talk about what I do.

While running:
    if filesFound != []:
         moveFiles
    else:
       time.sleep(1)
+3
source share
2 answers

One way to make non-blocking wait is to use threading.Event :

import threading
dummy_event = threading.Event()
dummy_event.wait(timeout=1)

set() , , - . , , - join :

import threading

def create_the_file(completion_event):
    # Do stuff to create the file

def Main():
    worker = threading.Thread(target=create_the_file)
    worker.start()

    # We will stop here until the "create_the_file" function finishes
    worker.join()

    # Do stuff with the file

, , ...

, . , dummy_threading, dummy_event.wait() . join().

, script, subprocess ( , , wait, , , ).

script, PID, os.waitpid(), OSError, ...

- , GIO FileMonitor PyGTK/PyGObject. monitor_directory GIO. .

:

import gio

def directory_changed(monitor, file1, file2, evt_type):
    print "Changed:", file1, file2, evt_type

gfile = gio.File(".")
monitor = gfile.monitor_directory(gio.FILE_MONITOR_NONE, None)
monitor.connect("changed", directory_changed) 

import glib
ml = glib.MainLoop()
ml.run()
+7

"subprocess" lib. Popen , . , , , .

,

import subprocess
help(subprocess)
-3

Source: https://habr.com/ru/post/1758223/


All Articles