Reputation: 19
I'm quite new on Python, and just can't figure out how I get this working.
What I want is a background while loop that prints every second something out, but can turn it off and on when I want to. For the example I just want to have it the first 4 seconds turned on, after that 4 seconds off (so nothing actually happens). I run it as an process.
#!/usr/bin/env python
import sys
import os
from multiprocessing import Process
from time import gmtime, strftime,sleep
## Start with false
switch = False
def logstate():
switchT = switch
while (switchT == True):
print('state')
sleep(1)
switchT = switch
if __name__ == '__main__':
# start process
p1 = Process(target=logstate())
p1.start()
p1.join()
# switch on
switch = True #?
sleep(4)
# switch off
switch = False #?
sleep(4)
So there is probably a lot of ways how to do this, but can't figure out what's the easiest way. Many thanks.
Upvotes: 1
Views: 633
Reputation: 3907
Your loop should always run, otherwise you would need a second loop to check if it should run the loop = redundant.
Also you are using the multiprocessing library, which means they won't share global variables inside the system, like threads would. SO... you need to save the switch in an outside context (like a DB, or config file) and have the loop check that before output.
def logstate():
while 1:
with open('myfile.txt', 'r') as f:
switch = f.readline()
if switch.lower() == "true":
print('state')
sleep(1)
Here is the problem with the above. Sleep blocks the thread. You really should think about context switching, like gevent.
Additional option, if you do go to gevent, you can use GIPC to open multiple processes as well as asynch threading inside each process AND share states between them. It works extremely well.
Upvotes: 1
Reputation: 474
I think you should run the while loop inside a Thread
from threading import Thread
from time import sleep
SHOULD_LOOP = False
def threaded_function():
while True:
if not SHOULD_LOOP: continue
print('state')
sleep(1)
if __name__ == "__main__":
thread = Thread(target = threaded_function)
thread.start()
while True:
SHOULD_LOOP = True
sleep(4)
SHOULD_LOOP = False
sleep(4)
thread.join()
print ("thread finished...exiting")
Upvotes: 2