Use while loop to listen for an event?

I am trying to write a small clipboard logger (for linux) that listens for an event (changing the contents of the clipboard) and writes the contents of the clipboard to a file (on-change).

What I came up with is a simple while loop with the pyperclip clipper module:

import pyperclip

recent_value = ""
while True:
    tmp_value = pyperclip.paste()
    if tmp_value != recent_value:
        recent_value = tmp_value
        with open(".clipboard_history.txt", "a") as f:
            f.write(recent_value + "\n")

So, my first question is: can I actually run a True loop to “listen”, or will it be too much memory or generally ineffective or bad practice?

And the second question: how can I run this in the background, like shell job management (ampersand)?

Should I go for a demon, such as the one offered here, or some kind of event loop or flow magic?

-, ( ), ( ) .

============================

edit: ! + : , ?

+4
4

, time.sleep(1) - , ( 0,1-2 , , /)

, , .

+2

, : True? "", ?

. ,

time.sleep(0.1)

script , . : ,

: , ()?

.

+1

, :

while True:
    tmp_value = pyperclip.paste()
    if tmp_value != recent_value:
        recent_value = tmp_value
        with open(".clipboard_history.txt", "a") as f:
            f.write(recent_value + "\n")

, script , , loop , threading :

from threading import Thread
t = Thread(target=your-func, args=[])
t.start()

def your-func(self):
    # your loop goes here
+1
source

To run a python file without a console, the extension must be .pyw, for example, when launched, logger.pywit will be launched without opening the python shell.

Hope this answers your question.

0
source

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


All Articles