Menu in RPi Python choice and run two subprocess and kill it - python-3.x

RPi + Python3. I need a menu with 4 options.
When option 'AA' -> blink_LED33, option 'BB' -> blink_LED35, option 'CC' -> stop_blink _LED33, option 'DD' -> stop_blink_LED35
I need a while loop in blinkLED33.py and blinkLED35.py
blinkLED33.py
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BOARD)
GPIO.setup(33, GPIO.OUT, initial=GPIO.LOW)
while True:
GPIO.output(33, GPIO.HIGH)
print("ON_33.")
sleep(1)
GPIO.output(33, GPIO.LOW)
print("OFF_33.")
sleep(1)
blinkLED35.py
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BOARD)
GPIO.setup(35, GPIO.OUT, initial=GPIO.LOW)
while True:
GPIO.output(35, GPIO.HIGH)
print("ON_35.")
sleep(1)
GPIO.output(35, GPIO.LOW)
print("OFF_33.")
sleep(1)
menu.py
import sys
import time
import subprocess
import os
(...)
class My_Keyboard:
(...)
if __name__ == "__main__":
(...)
if clickkey == 'AA':
#exec(open("blinkLED33.py").read());
#subprocess.run(["blinkLED33.py"])
#os.system('python blinkLED33.py')
p1 = subprocess.Popen(['python', 'blinkLED33.py'])
if clickkey == 'BB':
#exec(open("blinkLED35.py").read());
#subprocess.run(["blinkLED35.py"])
#os.system('python blinkLED35.py')
p2 = subprocess.Popen(['python', 'blinkLED35.py'])
if clickkey == 'CC':
p1.terminate()
if clickkey == 'DD':
p2.terminate()
(...)

Change python for python3.
p1 = subprocess.Popen(['python3', 'blinkLED33.py'])
p2 = subprocess.Popen(['python3', 'blinkLED35.py'])

Related

Script Multiprocessing dont finish all task, and also i get 100 cpu?

i need to ask if part of my script is correct, working "i think fine" but i think really i have somethink wrong, because still i get CPU 100% and so many time dont finish all task but after 50/100 task is like frozen.
Any info how to edit it ? Or Maybe just tell me where is the error ?
Thank you
Ps. I have inserted all the modules that the script requires and only the part that should be of interest for multiprocessing and also just firt part of the script.
Many Thanks
from __future__ import print_function
import sys
import os
import easygui
import pyautogui as py
import datetime
import pwinput
import json
from collections import Counter
import random
import string
import threading
import subprocess
import multiprocessing
import queue
from multiprocessing import cpu_count
from multiprocessing import Value, Lock, Process, Queue, current_process
import numpy as np
import grequests
import requests
from requests.exceptions import ConnectionError
from requests.exceptions import HTTPError
import time
from time import sleep
number_of_processes = cpu_count()
class Counter(object):
def __init__(self, initval=0):
self.val = Value('i', initval)
self.lock = Lock()
def increment(self):
with self.lock:
self.val.value += 1
def value(self):
with self.lock:
return self.val.value
def updateTitle(number_of_processes,number_of_task,counterhits,counterdone,countersl,countml,username):
while True:
hits = int(counterhits.value())
done = int(counterdone.value())
shtot = int(countersl.value())
maitot = int(countml.value())
remain_scan = number_of_task - hits
elapsed = time.strftime('%H:%M:%S', time.gmtime(time.time() - start))
ctypes.windll.kernel32.SetConsoleTitleW(f'Site Valid For: {number_of_task} | Started: {hits} | Complete: {done} | Remain: {remain_scan} | SL Found: {shtot} | ML Found: {maitot} | Threads: {number_of_processes} | Time elapsed: {elapsed} ! Licensed at: {username}')
sleep(0.3)
def worker_main(tasks_to_do,tasks_finished,counterhits,counterdone,countersl,countml):
while True:
try:
site = tasks_to_do.get_nowait()
if site is None:
break
except Queue.Empty:
break
except Queue.Full:
sleep(0.5)
continue
counterhits.increment()
do_work(site,counterhits,counterdone,countersl,countml)
tasks_finished.put(site + current_process().name)
counterdone.increment()
return True
def main():
global username
number_of_task = int(len(filter_data))
counterhits = Counter(0)
counterdone = Counter(0)
countersl = Counter(0)
countml = Counter(0)
tasks_to_do = Queue()
tasks_finished = Queue()
processes1 = []
prefix = ['http://']
# creating processes
for w in range(number_of_processes):
p1 = Process(target=worker_main, args=(tasks_to_do,tasks_finished,counterhits,counterdone,countersl,countml))
processes1.append(p1)
p1.start()
procs = [Process(target=updateTitle, args=(number_of_processes,number_of_task,counterhits,counterdone,countersl,countml,username), daemon=True) for i in range(1)]
for p in procs: p.start()
for site_il in filter_data:
site_or = site_il.rstrip("\n")
if (site_or.startswith("http://")) :
site_or = site_or.replace("http://","")
elif (site_or.startswith("https://")) :
site_or = site_or.replace("https://","")
site_or = site_or.rstrip()
site_or = site_or.split('/')[0]
if ('www.' in site_or) :
site_or = site_or.replace("www.", "")
sitexx = [sub + site_or for sub in prefix]
for site in sitexx:
tasks_to_do.put(site)
# completing process
for p1 in processes1:
p1.join()
for p in procs: p.join()
# print the output
while not tasks_finished.empty():
print(tasks_finished.get())
os.system('pause>nul')
return True
if __name__ == '__main__':
if sys.platform.startswith('win'):
# On Windows calling this function is necessary.
multiprocessing.freeze_support()
main()

Rotary encoder value looking sticky after using tkinter function " root.after"

I am quite new to python and tkinter ,I am working on a project where i give demand to slave device through rotary encoder value and reading feedback value from slave devices through communication.
I face issue when i use root.after () function .
Any suggestion regarding proper use of root.after () function so that my interrupt routine not affected welcome heartly.
Thank you.
Here is my code.
import pigpio
import tkinter as tk
from PIL import ImageTk,Image
import time
from RPi import GPIO
import serial
i="*00T%"
j="*01T%"
s=serial.Serial(port='/dev/ttyS0',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1)
class decoder: # class for decoding rotary encoder
def __init__(self, pi, gpioA, gpioB, callback):
----------
---------------
----------------
if __name__ == "__main__":
import RPi.GPIO as GPIO
import time
import pigpio
import tkinter as tk
import board
import busio
rpm=0
tor=0
pow=0
pi = pigpio.pi()
st=1
pos=0
def callback(way): # interrupt event sense on pin no 17,18
global pos
global st
if st ==1:
pos += way
if pos >= 9999:
pos=9999
if pos <= 0:
pos=0
var.set(pos)
print("pos={}".format(pos))
def rpm_update():
global rpm
s.write(str.encode(i))
print(i)
time.sleep(0.2)
if s.inWaiting():
rpm=s.readline(s.inWaiting())
rpm=rpm.decode('utf-8',errors='ignore')
rpm=rpm[5:-1]
print(rpm)
var2.set(rpm)
def tor_update():
global tor
s.write(str.encode(j))
print(j)
time.sleep(0.2)
if s.inWaiting():
tor=s.readline(s.inWaiting())
tor=tor.decode('utf-8',errors='ignore')
tor=tor[4:-1]
print(tor)
var3.set(tor)
def pow_update():
global rpm,tor,pow
try:
rpm=float(rpm)
tor=float(tor)
except ValueError:
pass
pow=int(rpm*tor/5252)
var4.set(pow)
def update():
rpm_update()
time.sleep(0.5)
tor_update()
time.sleep(0.5)
pow_update()
root.after(1000,update)
path="/home/pi/logo.png"
root=tk.Tk()
img=ImageTk.PhotoImage(Image.open(path))
panel=tk.Label(root,image=img)
panel.pack()
panel.place(x=195,y=10,height=50,width=80)
root.title("Dynalec")
root.geometry("500x600")
{
body of tkinter screen
}
decoder=decoder(pi, 17, 18, callback)
root.after(1000,update)
root.mainloop()
everything is working fine before root.after() function " root.after(1000,update)
but i need it because i have to read slave values in every sec and update in gui screen.
Adding as a answer because long for comments, will remove soon.
Try this out:
def update():
root.after(500,rpm_update)
root.after(500,tor_update)
root.after(500,pow_update)
root.after(1000,update)
Do let me know.

python module keep crashing

I am trying to create a doorbell with a raspberry pi zero. When I press the button it will send a picture to telegram. The module works but, after a few pressed the button the module crash.
and see an error in terminal:
* Error in `python3': double free or corruption (out): 0x01f306e8 *
or I get this error:
python3: malloc.c:2406: sysmalloc: Assertion `(old_top == initial_top
(av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE &&
prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) ==
0)' failed.
I hope somebody know how to fix the problem
thanks alot!
python
import time
import random
import datetime
import telepot
from telepot.loop import MessageLoop
from picamera import PiCamera
import pygame
from settings import getstring
import RPi.GPIO as GPIO
camera = PiCamera()
bot = telepot.Bot('TOKEN')
ring = 'tones/doorbell.mp3'
pin = 22
pressed = 0
pygame.mixer.init()
pygame.mixer.music.load(ring)
def sendpic(chat_id):
camera.resolution = (1024, 768)
camera.capture('snapshots/test.jpg')
photo = open('snapshots/test.jpg', 'rb')
bot.sendPhoto(chat_id, photo)
def handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
print('Got command: %s' % command)
if command == '/roll':
bot.sendMessage(chat_id, random.randint(1,6))
elif command == '/time':
bot.sendMessage(chat_id, str(datetime.datetime.now()))
pygame.mixer.music.play()
sendpic(chat_id)
MessageLoop(bot, handle).run_as_thread()
print('I am listening ...')
# Define GPIO -pins as standard
GPIO.setmode(GPIO.BCM)
# Define pin X as input and enable internal resistors
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# function for button press
while True:
input_state = GPIO.input(pin)
if input_state == False:
pressed = 1
else:
if pressed == 1:
print('Someone at the door.')
pygame.mixer.music.play()
pressed = 0
while 1:
time.sleep(10)

why a thread does not end

I'm trying to make an app to interact with an usb rfid reader on a Raspberry pi.
it looks like the solution is using the trheading module (otherwise the data entry leads to a disfunction)
After some essays I made an app that works... the first time. After that, a message error says "threads can only be started once"... so the interpretation is that the thread does not end naturally...why??
import time
import sys
import os
from tkinter import *
from tkinter.ttk import *
import threading
def activa_fil(self):
print ('activant fil')
fil.start()
def prova2():
print('hola')
print(Control.get())
print(NumCorr.get())
print(time.strftime("%H:%M:%S"))
DisplayCorr.config(text=NumCorr.get())
Llistacorr.insert(0, (Control.get(),NumCorr.get(), time.strftime("%H:%M:%S")))
marc.contador +=1
Contador.config (text=marc.contador)
print(marc.contador)
file = open("prova.txt", "a")
file.write(Control.get())
file.write(NumCorr.get())
file.write (time.strftime("%H:%M:%S"))
file.write('\n')
file.close()
NumCorr.after(500, NumCorr.delete(0,END))
def tick():
time_string = time.strftime("%H:%M:%S")
Hora.config(text=time_string)
Hora.after(200, tick)
def canvia_focus(self):
NumCorr.focus()
fil=threading.Timer(0.5, prova2)
marc = Tk()
marc.geometry('480x320')
marc.bind_all(''<'Key-Return'>'', activa_fil)
marc.contador =0
Control = Combobox(marc)
Control['values']=('sortida','can cuias','can campanya','papiol','sortida papiol', 'can olivero', 'ullastrell', 'coll olesa','pla fideuer','aeri', 'arribada')
Control.config(font="helvetica 30", )
Control.grid(column='0', row='0', columnspan='2')
Llistacorr = Listbox(marc)
Llistacorr.config(font='arial')
Llistacorr.grid_propagate(0)
Llistacorr.grid(column='0', row='1', rowspan='3')
DisplayCorr=Label(marc, font='Arial 10')
DisplayCorr.grid(column='1', row='1')
NumCorr = Entry(marc)
NumCorr.config(font='helvetica 6')
Control.bind('<<ComboboxSelected>>', canvia_focus)
NumCorr.grid(column='0', row='4', columnspan='2')
Contador=Label(marc, font='arial 30')
Contador.grid(column='1', row='2')
Hora=Label(marc, font='arial 30')
Hora.grid(column='1', row='3')
tick()
marc.mainloop()

Using multiprocessing and ProcessPoolExecutor simultaneously

I am trying to create a simple script for python3.5 that can execute heavy computer vision algorithms in parallel. I have created a process by multiprocessing.Process in main process.
Inside that process I create concurrent.futures.ProcessPoolExecutor. Spawned process submits tasks to processPoolExecutor and it works perfectly fine. But when I try to stop and join spawned process it hangs on join.
Also if replace processPoolExecuter to threadPoolExecuter everything works perfectly. What did I miss?
Here is main file:
import multiprocessing as mp
import queue as Queue
import numpy as np
import cv2
from time import sleep
import executer_debug
def worker(queue):
pExecutor = executer_debug.Worker()
pExecutor.set()
while True:
print("-->{}<--".format(pExecutor.get()))
sleep(1)
try:
income = queue.get_nowait()
break
except Queue.Empty:
pass
pExecutor.set()
print("<1>{}<1>".format(pExecutor.get()))
print("<2>{}<2>".format(pExecutor.get()))
def main():
queue = mp.Queue()
currProcess = mp.Process(target = worker, args=(queue,))
currProcess.start()
frame = np.zeros((480,640), dtype=np.uint8)
while True:
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
print("stopped")
queue.put("stop")
currProcess.join()
if __name__ == "__main__":
main()
And here is the second file. Code is very simple just enough to demonstrate the issue.
import collections
from concurrent.futures import ProcessPoolExecutor
from time import sleep
import multiprocessing as mp
def worker():
return 1
class Worker():
def __init__(self):
self.workers_count = 4
self.poolExecutor = ProcessPoolExecutor(max_workers = self.workers_count)
self.executors = collections.deque()
def set(self):
self.executors.append(self.poolExecutor.submit(worker))
def get(self):
if len(self.executors) > 0:
if self.executors[0].done():
return self.executors.popleft().result()
else:
return 0
else:
return -1
Thank you!

Resources