How to restart python multi-thread - python

I'm trying to design a control interface for my system which sends and receives some data through serial link. My searches related to GUI design took me to understand the "multi-threading" issue and code below shows the latest position I arrived.
This indicates similar parts (e.g try, run) with the ones I've seen on example GUIs. I planned to convert this to a GUI, once I understand how it exactly works.
So the problem is after I start, stop the code below I can't restart it again. Because, as I understand, multi-threading features only one cycle: start, stop and quit. I mean it doesn't accept start command after stop.
My question is how I can make this code to accept start after stopping?
Best wishes
import threading, random, time
class process(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
self.leave = 0
print("\n it's running ...\n\n")
while self.leave != 1:
print "Done!"
time.sleep(1)
operate = process()
while True:
inputt = input(" START : 1 \n STOP\t : 0 \n QUIT\t : 2 \n")
try:
if int(inputt) == 1:
operate.start()
elif int(inputt) == 0:
operate.leave = 1
elif int(inputt) == 2:
break
except:
print(" Wrong input, try egain...\n")

Create process inside while True loop
if int(inputt) == 1:
operate = process()
operate.start()
It should work.
... but your code may need other changes to make it safer - you will have to check if process exists before you try to stop it. You could use operate = None to control it.
import threading
import random
import time
class Process(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
self.leave = False
print("\n it's running ...\n\n")
while self.leave == False:
print("Done!")
time.sleep(1)
operate = None
while True:
inputt = input(" START : 1 \n STOP\t : 0 \n QUIT\t : 2 \n")
try:
if int(inputt) == 1:
if operate is None:
operate = Process()
operate.start()
elif int(inputt) == 0:
if operate is not None:
operate.leave = True
operate.join() # wait on process end
operate = None
elif int(inputt) == 2:
if operate is not None:
operate.leave = True
operate.join() # wait on process end
break
except:
print(" Wrong input, try egain...\n")
Other method is not to leave run() when you set leave = True but keep running thead. You would need two loops.
def run(self):
self.leave = False
self.stoped = False
print("\n it's running ...\n\n")
while self.leave == False:
while self.stoped == False:
print("Done!")
time.sleep(1)

Related

Possible memory leak in Python?

I'm experiencing an issue when calling a function inside a while loop.
The purpose of the while loop is to perform an action ,but it can only perform this action if a certain threshold appeared. This threshold is a result from another function.
When running this for the first time ,everything works ok. No threshold -no run.
The problem is ,that this threshold is affected by other parameters ,and when it changes ,it usually blocks the main program from running.
But ,at certain times, which I cannot pinpoint precisely when ,there's a "slip" and the threshold does not prevent the main program from running.
My question is ,could there be a memory leakage of some sort?
Code is below ,thanks.
def pre_run_check():
if check_outside() != 1:
return (0)
else:
return(1)
if __name__== '__main__':
while True:
time.sleep(0.5)
allow_action = None
while allow_action == None:
print ("cannot run")
try:
allow_action = pre_run_check()
except:
allow_action = 0
else:
if allow_action == 1:
print ("running")
#take action of some sort##
allow_action = None
def pre_run_check():
if check_outside() != 1:
return False
else:
return True
while True:
time.sleep(0.5)
allow_action = pre_run_check()
while not allow_action:
print ("cannot run")
try:
allow_action = pre_run_check()
if allow_action :
print ("running")
#take action of some sort##
allow_action = False
#Actualy need wait end of subprocess, Otherwise got some corrupted data/handle
break
except:
allow_action = False
time.sleep(.5)
This point is how to generate an sequential Process
Hope its helps.

input() returns EOF Error while Multithreading

So I wanted to make my own Omegle interface in Python to get some practice with the language, and also it just sounded like fun. In order to handle the inputs and outputs at the same time, I've decided to use multithreading. This is my first time working with multithreading, so I don't really know what I am doing. Whenever I try and use input() while in a multithreaded function, it returns an EOF error. Any idea how to get around it, or if I'm going about this the entirely wrong way, what is a better way to do this?
Code:
from python_omegle import InterestsChat
from python_omegle import ChatEvent
from multiprocessing import Process
import sys
def start_chat_loop():
interests = input("Please input interests: ").split
chat = InterestsChat(interests)
chat_loop(chat=chat)
p2 = Process(target = take_input)
p2.start()
def take_input():
while True:
i = input()
if(i == "/next"):
chat.disconnect()
else:
print("You: typing...")
chat.send(i)
print("You: "+i)
def chat_loop(chat):
while True:
# Start a new chat every time the old one ends
print("- Starting chat -")
chat.start()
while True:
event, argument = chat.get_event()
if event == ChatEvent.CHAT_WAITING:
print("- Waiting for a partner -")
elif event == ChatEvent.CHAT_READY:
common_interests = argument
print("- Connected, common interests: {} -".format(*common_interests))
break
# Connected to a partner
while True:
event, argument = chat.get_event()
if event == ChatEvent.GOT_SERVER_NOTICE:
notice = argument
print("- Server notice: {} -".format(notice))
elif event == ChatEvent.PARTNER_STARTED_TYPING:
print("- Partner started typing -")
elif event == ChatEvent.PARTNER_STOPPED_TYPING:
print("- Partner stopped typing -")
elif event == ChatEvent.GOT_MESSAGE:
message = argument
print("Partner: {}".format(message))
elif event == ChatEvent.CHAT_ENDED:
print("- Chat ended -")
break
if __name__ == "__main__":
p1 = Process(target = start_chat_loop)
p1.start()
Problem spots:
def start_chat_loop():
interests = input("Please input interests: ").split
chat = InterestsChat(interests)
chat_loop(chat=chat)
p2 = Process(target = take_input)
p2.start()
def take_input():
m = False
while True:
i = input()
if(i == "/next"):
chat.disconnect()
else:
print("You: typing...")
caht.send(i)
print("You: "+i)
Does your chat.disconnect() method have a way of escaping an endless loop? I'm not too advanced with this but I believe you should either do:
if(i == "/next"):
chat.disconnect()
break
or
def take_input():
m = False
while not m:
i = input()
if(i == "/next"):
chat.disconnect()
m = True
else:
print("You: typing...")
chat.send(i)
print("You: "+i)
I also noticed in the 2nd block of code that its written:
caht.send(i) instead of chat.send(i). A syntax error might be preventing the loop of ending as well thus resulting in EOF.

Threading with Python

complete python newbie...
I'm working with the Arduino pyfirmata package and Im trying to do something quite simple.
Depending on a user input to python, I want an LED to flash or not.
My problem is that the python program only asks for the user input once but I would like it to always ask for the input so the user can change function at any time.
I have tried using the threading package but no success... Perhaps there is a simpler way, but I am totally new to coding so I do not know of any other. Open to suggestions!!
Here is my code,
import pyfirmata
import threading
import time
board = pyfirmata.Arduino('/dev/cu.usbmodem14101')
def flash():
for i in range(1000):
board.digital[13].write(1)
time.sleep(1)
board.digital[13].write(0)
time.sleep(1)
def stop():
board.digital[13].write(0)
while True:
runMode = input("Run or Stop? ")
if runMode == "Run":
x = threading.Thread(target=flash(), args=(1,))
x.start()
# x.join()
elif runMode == "Stop":
x = threading.Thread(target=stop(), args=(1,))
x.start()
#x.join()
You can do it in an object-oriented way by creating your own Thread subclass something like the Flasher class below.
One of the advantages to this approach is that it would be relatively easy to extend the Flasher class and make it control LEDs connected to different outputs, or to allow the delay between flashes to be specified at creation time. Doing the former would allow multiple instances to be running at the same time.
import pyfirmata
import threading
import time
OFF, ON = False, True
class Flasher(threading.Thread):
DELAY = 1
def __init__(self):
super().__init__()
self.daemon = True
self.board = pyfirmata.Arduino('/dev/cu.usbmodem14101')
self.flashing = False
self.LED_state = OFF
def turn_LED_on(self):
self.board.digital[13].write(1)
self.LED_state = ON
def turn_LED_off(self):
self.board.digital[13].write(0)
self.LED_state = OFF
def run(self):
while True:
if self.flashing:
if self.LED_state == ON:
self.turn_LED_off()
else:
self.turn_LED_on()
time.sleep(self.DELAY)
def start_flashing(self):
if self.LED_state == OFF:
self.turn_LED_on()
self.flashing = True
def stop_flashing(self):
if self.LED_state == ON:
self.turn_LED_off()
self.flashing = False
flasher = Flasher()
flasher.start()
while True:
runMode = input("Run or Stop? ").strip().lower()
if runMode == "run":
flasher.start_flashing()
elif runMode == "stop":
flasher.stop_flashing()
else:
print('Unknown response ignored')
If your looking to just kill the thread you could use mulitiprocessing
which a multiprocessing.Process can p.terminate()
p = Process(target=flash, args=(,))
while True:
runMode = input("Run or Stop? ")
if runMode == "Run":
p.start()
elif runMode == "Stop":
p.terminate()
However this is not recommended to just kill threads as it can cause errors if the process is handling critical resources or dependant on other threads see here for a better explanation Is there any way to kill a Thread?
A better option as described here is to use flags to handle your flashing, they allow a simple communication between threads
from threading import Event
e = event()
def check_for_stop(e):
while not e.isSet():
flash()
print("Flashing Ended")
while True:
runMode = input("Run or Stop? ")
if runMode == "Run":
x = threading.Thread(target=check_for_stop, args=(e,))
x.start()
# x.join()
elif runMode == "Stop":
e.set() #set flag true
e.clear() #reset flag
here is the documentation for more info on event objects https://docs.python.org/2.0/lib/event-objects.html
I havent tested this code is just an example so apologies if it doesnt work straight away
Edit: Just looking at your function again you would want to check for the flag during the flashing thats my mistake aplogies so your flash function would look like
def flash():
while e.isSet():
board.digital[13].write(1)
time.sleep(1)
board.digital[13].write(0)
time.sleep(1)
and you would pass this into the thread as you have before
x = threading.Thread(target=flash(), args=(1,))
x.start()
You got an error in the code.
You should create the thread via:
x = threading.Thread(target=flash)
Note: You gave the entered 'flash()' therefore executing the method in the main thread. And also your method doesn't have any arguments therefore you can remove the args values

Fabric get() progressbar

I am currently generating a python-script with the fabric framwork that is supposed to collect a backup from a remote server and store it locally on the client running fabric.
Now, since the backup file is >400MB, it takes quite some time to transfer it. And here is where my question bumps in:
Is there any kind of progressbars for the fabric get()-function? Or rather, is it possible to add a progressbar somehow?
Here's a piece of my code:
def collect_backup():
env.warn_only=True
run('uptime')
print "Copying scrips to be run..."
filename, remotepath = _getlatest()
print "Copy complete."
print "Collecting backup..."
localpath = _collect(filename, remotepath)
def _collect(filename, remotepath):
a=remotepath + filename
localpath="/home/bcns/backups/"
####Here's the get() I was talking about
get(a, localpath)
return(localpath)
The "filename" and "remotepath" variables are set in another function.
There is a lot of great info at the following site:
http://thelivingpearl.com/2012/12/31/creating-progress-bars-with-python/
Here is their solution for a console prog bar with threading:
import sys
import time
import threading
class progress_bar_loading(threading.Thread):
def run(self):
global stop
global kill
print 'Loading.... ',
sys.stdout.flush()
i = 0
while stop != True:
if (i%4) == 0:
sys.stdout.write('\b/')
elif (i%4) == 1:
sys.stdout.write('\b-')
elif (i%4) == 2:
sys.stdout.write('\b\\')
elif (i%4) == 3:
sys.stdout.write('\b|')
sys.stdout.flush()
time.sleep(0.2)
i+=1
if kill == True:
print '\b\b\b\b ABORT!',
else:
print '\b\b done!',
kill = False
stop = False
p = progress_bar_loading()
p.start()
try:
#anything you want to run.
time.sleep(1)
stop = True
except KeyboardInterrupt or EOFError:
kill = True
stop = True
Hope that helps or at least gets you started.

Constantly looking for user input in Python

How would I write a Python program that would always be looking for user input. I think I would want to have a variable equal to the input and then something different would happen based on what that variable equaled. So if the variable were "w" then it would execute a certain command and keep doing that until it received another input like "d" Then something different would happen but it wouldn't stop until you hit enter.
If you want to constantly look for an user input you'll need multithreading.
Example:
import threading
import queue
def console(q):
while 1:
cmd = input('> ')
q.put(cmd)
if cmd == 'quit':
break
def action_foo():
print('--> action foo')
def action_bar():
print('--> action bar')
def invalid_input():
print('---> Unknown command')
def main():
cmd_actions = {'foo': action_foo, 'bar': action_bar}
cmd_queue = queue.Queue()
dj = threading.Thread(target=console, args=(cmd_queue,))
dj.start()
while 1:
cmd = cmd_queue.get()
if cmd == 'quit':
break
action = cmd_actions.get(cmd, invalid_input)
action()
main()
As you'll see this, will get your messages a little mixed up, something like:
> foo
> --> action foo
bar
> --> action bar
cat
> --> Unknown command
quit
That's beacuse there are two threads writing to stdoutput at the same time. To sync them there's going to be need of lock:
import threading
import queue
def console(q, lock):
while 1:
input() # Afther pressing Enter you'll be in "input mode"
with lock:
cmd = input('> ')
q.put(cmd)
if cmd == 'quit':
break
def action_foo(lock):
with lock:
print('--> action foo')
# other actions
def action_bar(lock):
with lock:
print('--> action bar')
def invalid_input(lock):
with lock:
print('--> Unknown command')
def main():
cmd_actions = {'foo': action_foo, 'bar': action_bar}
cmd_queue = queue.Queue()
stdout_lock = threading.Lock()
dj = threading.Thread(target=console, args=(cmd_queue, stdout_lock))
dj.start()
while 1:
cmd = cmd_queue.get()
if cmd == 'quit':
break
action = cmd_actions.get(cmd, invalid_input)
action(stdout_lock)
main()
Ok, now it's better:
# press Enter
> foo
--> action foo
# press Enter
> bar
--> action bar
# press Enter
> cat
--> Unknown command
# press Enter
> quit
Notice that you'll need to press Enter before typing a command to enter in "input mode".
from http://www.swaroopch.com/notes/Python_en:Control_Flow
#!/usr/bin/python
# Filename: while.py
number = 23
running = True
while running:
guess = int(input('Enter an integer : '))
if guess == number:
print('Congratulations, you guessed it.')
running = False # this causes the while loop to stop
elif guess < number:
print('No, it is a little higher than that.')
else:
print('No, it is a little lower than that.')
else:
print('The while loop is over.')
# Do anything else you want to do here
print('Done')
Maybe select.select is what you are looking for, it checks if there's data ready to be read in a file descriptor so you can only read where it avoiding the need to interrupt the processing (well, in the example it waits one second but replace that 1 with 0 and it'll work perfectly):
import select
import sys
def times(f): # f: file descriptor
after = 0
while True:
changes = select.select([f], [], [], 1)
if f in changes[0]:
data = f.readline().strip()
if data == "q":
break
else:
print "After", after, "seconds you pressed", data
after += 1
times(sys.stdin)
if you want to get input repeatedly from user;
x=1
while x==1:
inp = input('get me an input:')
and based on inp you can perform any condition.
You can also use definitions, say, something like this:
def main():
(your main code)
main()
main()
though generally while loops are much cleaner and don't require global variables :)

Categories

Resources