Terminate loop at any given time
<p>I have the following code which turns an outlet on/off every 3 seconds.</p>

<pre><code>    start_time = time.time()
    counter  = 0
    agent = snmpy4.Agent("192.168.9.50")

    while True:
        if (counter % 2 == 0):
            agent.set("1.3.6.1.4.1.13742.6.4.1.2.1.2.1.1",1)
        else:
            agent.set("1.3.6.1.4.1.13742.6.4.1.2.1.2.1.1", 0)

        time.sleep(3- ((time.time()-start_time) % 3))
        counter = counter + 1
</code></pre>

<p>Is there a way I can have the loop terminate at any given point if something is entered, (space) for example... while letting the code above run in the mean time</p>

<p>You can put the loop in a thread and use the main thread to wait on the keyboard. If its okay for "something to be entered" can be a line with line feed (e.g., type a command and enter), then this will do</p>

<pre><code>import time
import threading
import sys

def agent_setter(event):
    start_time = time.time()
    counter  = 0
    #agent = snmpy4.Agent("192.168.9.50")

    while True:
        if (counter % 2 == 0):
            print('agent.set("1.3.6.1.4.1.13742.6.4.1.2.1.2.1.1",1)')
        else:
            print('agent.set("1.3.6.1.4.1.13742.6.4.1.2.1.2.1.1", 0)')

        if event.wait(3- ((time.time()-start_time) % 3)):
            print('got keyboard')
            event.clear()
        counter = counter + 1

agent_event = threading.Event()
agent_thread = threading.Thread(target=agent_setter, args=(agent_event,))
agent_thread.start()

for line in sys.stdin:
    agent_event.set()
</code></pre>

python loops break