I have made a script that checks 100 times whether an image can be detected. He clicks it if it is seen in the last if statement. But a few things are going wrong here.
1: He doesn't right-click what I do.
2: after clicking my script closes immediately!
What did I do wrong? and how do I fix this?
This is my code
import os
import pyautogui
import time
import subprocess
def openprogram():
#opens program
subprocess.call(["cmd", "/c", "start", "/max", "D:\FarmHelper3.exe"])
def inloggen():
#searches for image 100 times to login
for _ in range(100):
time.sleep(1)
coords = pyautogui.locateOnScreen('images/login.png')
#if he has not found the photo within the program
if coords == None:
print ("Geen login gevonden")
#if the picture is found
if coords != None:
print ("Login gevonden")
pyautogui.rightClick(coords)
openprogram()
inloggen()
Related
I am trying to make a simple AFK script for if I need to leave my pc for short period and the code works on it's own but when I try to use one script to run another, It runs but then stops a few seconds later with exit code 0. I'm not sure what's wrong and I've tried multiple things such as:
import test1
test1.run()
And that doesn't seem to work. Every site I find tells me to use the above example or stuff such as exec which I've been told is dangerous. Note: a text file named 'bridge' will have to be created so the file can be stopped
main.py
import os
from output import run
import keyboard
from time import sleep
print('Start afk program? (Y/N)')
cmd = str.lower(input('> '))
if cmd == 'y':
print('Use X to Stop')
print('Starting in 10 seconds...')
run()
while True:
if keyboard.is_pressed('x'):
print('exit key pressed')
x = '1'
else:
x = '0'
if os.path.exists('bridge.txt'):
with open('bridge.txt', 'w') as file:
file.write(x)
file.write('\n')
file.close()
else:
exit('file not found')
if x == '1':
exit(0)
sleep(0.1)
output.py
import os
from time import sleep
from pynput.keyboard import Controller
keyboard = Controller()
def run():
global keyboard
sleep(10)
keyboard = Controller()
count = 0
while True:
if os.path.exists('bridge.txt'):
with open('bridge.txt', 'r') as file:
content = file.readlines()
for line in content:
if line[0] == '1':
exit(0)
if count == 1:
press_key('w')
elif count == 2:
press_key('a')
elif count == 3:
press_key('s')
elif count == 4:
press_key('d')
elif count == 10:
count = 0
press_key('q')
count += 1
sleep(0.1)
def press_key(key):
keyboard.press(key)
sleep(0.5)
keyboard.release(key)
run()
I get that having the two systems apart can be easily avoided and will be fixed later, but the answer to this question will help me with other projects
For me (Python 3.8), your code works fine if you simply type on the terminal
python main.py
provided that you comment out or delete the last line in output.py:
# run()
which would execute function run upon importing output in main. The program also works if I import from a local module
import output
output.run()
If for some reason you're trying to import output from a different directory, you may have to deal with relative imports -- a subject nothing to do with the specific implementation of your scripts.
This code seems to have couple of problems from initial check.
Since you are calling run() before the if keyboard.is_pressed('x'):, it will always run in infinite loop.
Also, if line[0] == '1':, this needs to be changed to if line[-1] == '1': to check the last character entered, but since the code never reached the line to take x as input, entering a value x will not work either.
There are logical errors here.
Im trying to print a gif in my homework game if someone wins or loses, and for that I have this code:
import shutil
import pyglet
import requests
import os
def gif():
url = 'https://tenor.com/view/no-oh-no-nope-nah-not-really-gif-15162749.gif'
filename = url.split('/')[-1]
with open(filename, 'wb') as out_file:
out_file.write(requests.get(url).content)
os.rename('no-oh-no-nope-nah-not-really-gif-15162749.gif', 'michaelscott1.gif')
animation = pyglet.image.load_animation('michaelscott1.gif')
animSprite = pyglet.sprite.Sprite(animation)
w = animSprite.width
h = animSprite.height
window = pyglet.window.Window(width=w, height=h)
#window.event
def on_draw():
window.clear()
animSprite.draw()
pyglet.app.run()
gif()
If I run it the program it shows the gif, and when I close it, the program finishes with exit code 0.
If I put a print statement after it, it shows the gif, prints the print and then finishes with exit code 0.
But if I try to make an input statement after the gif
input('>')
The python window showing the gif crashes. And when I force close it, the script quits, and I get this return statement:
Process finished with exit code 143 (interrupted by signal 15: SIGTERM)
What is the solution to this?
Assuming you switch to Python3 (which you should), things might start to work a little bit better.
Some improvements if nothing else to the code, would be to not store the image on disk unless you really need to.
You can circumvent this by using io.BytesIO and load the image from within memory:
import pyglet
import os
import urllib.request, io
def url_to_sprite(url):
with urllib.request.urlopen(url) as response:
image_data = response.read()
image = pyglet.image.load_animation(os.path.basename(url), file=io.BytesIO(image_data))
return pyglet.sprite.Sprite(image)
animSprite = url_to_sprite('https://media.giphy.com/media/13gvXfEVlxQjDO/giphy.gif')
input('>')
window = pyglet.window.Window(width=animSprite.width, height=animSprite.height)
#window.event
def on_draw():
window.clear()
animSprite.draw()
pyglet.app.run()
I can't reproduce any errors with this code. And nothing crashes when using the input.
The program will however not render anything until after the input is completed.
This is my Code to start my other Code where i defined my Laser to start.
But in this Code i want to have a Button which starts my other script if i put press it.
But what this code does is it activate my code continuous.
What can i change in it ?
#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
import os
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
#GPIO.setmode(GPIO.BOARD)
GPIO.setup(15,GPIO.IN) #GPIO17
#input = GPIO.input(27)
#print ("input",input)
while True :
#inputValue = GPIO.input(11)
#print ("input01",inputValue)
#time.sleep(1)
erg= GPIO.wait_for_edge(15,GPIO.RISING, bouncetime=20)
print ("Input",2)
#if (GPIO.input(11) == GPIO.HIGH):
#if erg==15:
print ("Input",1)
time.sleep(3)
#inputValue = 1
os.system("python /home/pi/gpio.py")
When you run os.system('python /home/pi/gpio.py') you start new process and your main process get back to work on its while loop.
As I understood your idea was to wait until button is pressed and then go to some other state waiting for something new to happen.
You don't need to start new process just import module (doc). When button was clicked break loop and run code from the imported module.
Also you may find it interesting to replace wait_for_edge with event_detected method. More about it here.
For the extraction of text from a chat window I started off by gathering the window handles.
I managed doing this by the following code:
import time, win32gui
def callback(hwnd, IEServers):
if win32gui.GetClassName(hwnd) == 'Internet Explorer_Server':
IEServers.append(hwnd)
print "IE server found:", hwnd
time.sleep(3)
mainHwnd = win32gui.GetForegroundWindow()
IEServers = []
win32gui.EnumChildWindows(mainHwnd, callback, IEServers)
for serv in IEServers:
print win32gui.GetClassName(serv)
Next thing I want to do is get the content (inner html?) as a string.
I believe it can be done via a IHTMLDocument2 object.
Info: http://support.microsoft.com/kb/q249232
How to do this?
You can try something like this. Maybe not exactly what you want but should get you on your way:
import time, win32gui
import win32com.client
time.sleep(2)
mainHwnd = win32gui.GetForegroundWindow()
s = win32com.client.Dispatch("Shell.Application")
for w in s.Windows():
if int(w.Hwnd) == mainHwnd:
print w.LocationURL
print w.Document.body.innerText
print w.Document.body.innerHTML
break
I think innerText is what you want, but I included several attributes so you can take your pick. This will only work with IE, of course.
I am new to python and I am trying to write a script that exits out of a loop when a certain window closes. I am having problems getting the code to work properly it won't even enter the loop. I think this is because I am not properly getting the window name. I was wondering if there are any good tutorials on the Win32Gui extension that would help me to understand how it works.
Edit
Here is what I have, it is doing what it is suppose to do, but I am sure there is an easier way of doing it.
def answerCalls(local, network):
t = 0
count = 0
while t == 0:
time.sleep(1)
if win32gui.GetWindowText(win32gui.GetForegroundWindow()) == "Incoming Call":
time.sleep(10)
getApplicationPos("Incoming Call")
clickOnElement(******.IncomingCall_AnswerButton())
time.sleep(10)
if win32gui.GetWindowText(win32gui.GetForegroundWindow()) == "Video Call":
count += 1
writeFile("Answering Calls", count, local)
uploadToServer(local, network)
The following example (Python 3) gets a list of the titles of all the windows:
import win32gui
def enum_window_titles():
def callback(handle, data):
titles.append(win32gui.GetWindowText(handle))
titles = []
win32gui.EnumWindows(callback, None)
return titles
titles = enum_window_titles()