I was writing code to take a screenshot of a math equation then type out the answer, but it outputs "None" every 5th or so time. Was wondering if this was in some way fixable or if I should just scrap the idea. Thanks in advance :)
from pyautogui import *
import pyautogui
import time
import keyboard
import random
import win32api, win32con
import cv2
import pytesseract
from pynput.keyboard import Key, Controller
def main():
try:
while keyboard.is_pressed('q') == False:
win32api.SetCursorPos((80,60))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
time.sleep(1)
win32api.SetCursorPos((350,370))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
time.sleep(1)
while keyboard.is_pressed('q') == False:
iml = pyautogui.screenshot(region=(190,270,275,150)) #screenshot
iml.save(r'C:\Users\USER\Desktop\New folder\my_screenshot.png')
pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract'
math = (pytesseract.image_to_string(r'C:\Users\USER\Desktop\New folder\my_screenshot.png'))
math = math.replace('+', '/')
math = math.replace('x', '*')
math = math.replace('X', '*')
if exec(math) == 'None':
math = eval(math)
else:
math = exec(math)
math = str(math)
print(math)
time.sleep(0.5)
for char in math:
keyboard.press(char)
keyboard.release(char)
except:
main()
main()
Related
im a beginner in python and i have a big trouble for this code. im making a small match making game and this game made me hate python.
simply, user should match the photos together and try to do it as fast as possible for getting less time.
however, the timer is never working or giving me recursion limit error.
i want a simple second counter and a way to count the score.
so far, this is what i have and the timer is happening only once. so the label just becoming 1
import mycanvas as mc
import tkinter as tk
import random as r
import time
clickedimages=[]
score = 0
seconds=0
def main():
root=tk.Tk()
root.geometry("550x800")
root.resizable(0,0)
coverimg=tk.PhotoImage(file="pics\\qs.png")
name=""
images=[]
coppyimages=[]
allcanvas=[]
lbl=tk.Label(root,text="0",font=('robot',20))
lbl2=tk.Label(root,text=str(score),font=('robot',20))
lbl.place(x=100,y=750)
lbl2.place(x=400,y=750)
#making images
for x in range(1,11):
name="pics\\p"+str(x)+".png"
images.append(tk.PhotoImage(file=name))
coppyimages.append(tk.PhotoImage(file=name))
coppyimages.append(tk.PhotoImage(file=name))
#5x4
#positioning
tx=50
ty=150
counter=1
for x in range(0,5):
for y in range (0,4):
choice=r.randint(0,len(coppyimages)-1)
allcanvas.append(mc.myconvas(root,counter,coppyimages.pop(choice),tx,ty,coverimg))
tx+=120
counter+=1
tx=50
ty+=120
root.after(1000,timer(lbl))
root.mainloop()
def timer(lbl):
global seconds
seconds+=1
lbl.configure(text=str(seconds))
def clicked(event):
if(len(clickedimages)==0):
event.widget.showorhide()
clickedimages.append(event.widget)
elif((len(clickedimages)>0) and (event.widget != clickedimages[0])):
event.widget.showorhide()
clickedimages.append(event.widget)
matchchecker()
def matchchecker():
global clickedimages,score
time.sleep(0.5)
if(clickedimages[0].nameofimage==clickedimages[1].nameofimage):
print("Its a match")
clickedimages[0].place_forget()
clickedimages[1].place_forget()
score+=1
else:
print("wrong :(")
clickedimages[0].showorhide()
clickedimages[1].showorhide()
clickedimages.clear()
gamechecker()
def gamechecker():
global score
if(score==10):
print("Game over")
if __name__ == '__main__':
main()
the class is :
import tkinter as tk
import main
class myconvas(tk.Canvas):
number=0
myimage=None
nameofimage=""
coverimg=None
show=True
def __init__(self, root,n,img,px,py,dfault):
super().__init__()
self["width"] = 100
self["height"] = 100
self.number=n
self.myimage=img
self.maketheimage(dfault,px,py)
self.nameofimage = img.cget('file')
# self.setimagename()
self.coverimg=dfault;
self.bind("<Button-1>",main.clicked)
# root.after(500,self.showorhide())
def maketheimage(self,img,px,py):
self.create_image(50,50,image=img,anchor='center')
self.place(x=px,y=py)
def setimagename(self):
self.nameofimage=self.myimage.cget('file')
def showorhide(self):
if(self.show):
self.create_image(50,50,image=self.myimage,anchor='center')
self.show=False
else:
self.create_image(50,50,image=self.coverimg,anchor='center')
self.show=True
thank you in advance
import time
import pyautogui
from pyautogui import *
import keyboard
from PIL import ImageGrab, Image
from PIL import *
import os
import win32api, win32con
import cv2
import pyperclip
from pynput.keyboard import Key, Listener
import pytesseract
import numpy as np
from numpy import *
from threading import Event
##1340,182, 1777, 213
test = 0
src_path = os.getcwd()
pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract'
def get_region(box):
im = ImageGrab.grab(box)
im = im.save(os.getcwd() + "\\logs.png", 'PNG')
def get_string(img_path):
img = cv2.imread(img_path)
kernel = np.ones((1, 1), np.uint8)
img = cv2.dilate(img, kernel, iterations=1)
img = cv2.erode(img, kernel, iterations=1)
red = [0,0,255]
img[img != red] = 255
cv2.imwrite(src_path + "\\logs.png", img)
result = pytesseract.image_to_string(Image.open(src_path + "\\logs.png"))
return result
def alertf1(c):
global test
time.sleep(0.1)
while c == 1:
if keyboard.is_pressed('f1'): # if key 'f1' is pressed
print('f1 has been pressed')
c = 0
break
else:
result = get_string(src_path + "\\logs.png")
print('checking if anything is destroyed')
if result.find('destroved') != -1:
print('something got destroyed!')
pyautogui.keyDown('ctrl')
time.sleep(0.1)
pyautogui.keyDown('tab')
pyautogui.keyUp('ctrl')
pyautogui.keyUp('tab')
time.sleep(0.5)
for char in '#':
pyperclip.copy(char)
pyautogui.hotkey('ctrl', 'v', interval=0.1)
pyautogui.write('everyone Enemies/Red Logs! Something has been destroyed.')
pyautogui.press('enter')
pyautogui.click(x=1860, y=50)
else:
if keyboard.is_pressed('f1'): # if key 'f1' is pressed
print('f1 has been pressed')
c = 0
break
def on_press(key):
global test
test = test + 1
region = (1341,185, 1778, 215)
get_region(region)
if key == Key.f1 and test == 1:
print('before alert f1 pressed')
test = test + 1
time.sleep(0.1)
alertf1(1)
if key == Key.f1 and test == 3:
test = 0
with Listener(on_press=on_press) as listener:
listener.join()
def main():
while True:
print('on press going now')
on_press(key)
if __name__ == '__main__':
main()
Thats my current code, a small explanation of what it does and what I want:
Upon start, if user presses 'F1' it will take a screenshot of a small area and turn the image into text, it will then run an infinite loop, to check if the text I got from the image is = to 'destroyed' if it is then user gets notified and if it isn't it will be on a infinite loop getting new screenshots and checking it again.
I also added the "if keyboard.is_pressed('f1'):" to break the infinite loop.
The 2 issues I have right now:
1- After user gets notified I want the program to not proceed into the infinite loop for 5 minutes, time.sleep (300) works but the issue is that if the user wants to cancel the current function and presses F1 to break the loop back into Main() it will not get detected, thus I need another alternative to time.sleep because it just freezes the code completely. I heard that threading.event could work but I have honestly no idea how it works, and even after checking a couple examples I am not sure how I could make it work still.
2- I found that 'if keyboard.is_pressed('f1'):' Isn't very effective as it sometimes doesn't trigger and have to click quite a few times until it triggers and breaks loop. What would be a good alternative?
import threading
import time
import os
def clearAfter15():
clear = lambda: os.system('clear/cls')
clear()
string_variable="This message will be disappear after 1 minutte"
t = threading.Timer(1*60, clearAfter15)
t.start()
print(string_variable)
Expected : After 1 minute the output will get disappeared from the console
Try this:
def clearAfter15():
clear = lambda: os.system('cls' if os.name == 'nt' else 'clear')
clear()
This is my code yet. I am able to play the song in background and get input from the keyboard, but I can't stop the music process in the keyboard process. Even with that flag I couldn't managed to terminate process p.
import os
import sys
from playsound import playsound
import msvcrt
import threading
from ctypes import c_buffer, windll
from random import random
from time import sleep
from sys import getfilesystemencoding
import multiprocessing
file = open('toplay.txt')
to_listen = []
n = file.readline()
def Get_Path(name):
path = os.getcwd() + '\\' + name + ".mp3"
return path
for i in range (int(n)):
name = file.readline()
if i <= int(n)-2:
name = name[:-1]
to_listen.append(Get_Path(name))
flag = 0
def Check_Keyboard():
while True:
pressedKey = msvcrt.getch()
key = bytes.decode(pressedKey)
print(key)
if key == 's':
flag = 1
if __name__ == '__main__':
for i in range(int(n)):
p = multiprocessing.Process(target=playsound(to_listen[i],
False))
p.start()
q = multiprocessing.Process(target = Check_Keyboard)
q.start()
if flag == 1:
p.terminate()
how should the code look so the below script runs only between 06.30h and 8.00h??
best regards
#!/usr/bin/python
from time import strftime
import sys
import subprocess from subprocess
import Popen
import pifacedigitalio
from time import sleep
pfd = pifacedigitalio.PiFaceDigital() # creates a PiFace Digital
object testprocess = None
while strftime('%H:%M') >= '06:29':
while(True):
sleep(0.1)
if pfd.input_pins[0].value == 1 and not testprocess:
subprocess.Popen(["/bin/myscript"])
testprocess = Popen(["/bin/myscript1"])
if pfd.input_pins[0].value == 0:
if testprocess:
testprocess.kill()
testprocess = None
subprocess.Popen(["/bin/mycript"])
sleep(1)
if strftime('%H:%M') == '08:00':
sys.exit()
I would do it with something like this:
from time import strftime
import sys
while strftime('%H:%M') >= '18:00':
#Your code
if strftime('%H:%M') == '20:30':
sys.exit()
You can learn more about time module here: https://docs.python.org/2/library/time.html
just get time into a time struct and compute the number of minutes from midnight, test the time window in minutes:
lt = time.localtime()
minutes = 60*lt.tm_hour + lt.tm_min
if 60*6+30 <= minutes <= 60*8:
subprocess.Popen(["/bin/myscript"])
testprocess = Popen(["/bin/myscript1"])