I am making a macro that uses pyautogui. I want to check the screen every so often for an image, and if the image is not found, the program breaks. The only problem that I am facing is that pyautogui never locates the image and fails it every time the program is started. I have tried to fix this in multiple ways but I am unable to do so, please help.
import pyautogui
import time
import random
import sys
import keyboard
import tkinter as tk
from tkinter import filedialog, Text
import os
#y is click
thent = time.time()
def island_check():
while time.time() - thent > 1:
t = pyautogui.locateOnScreen(r'C:\Users\myname\Desktop\Picture_bar.png', confidence=0.7)
if t == None:
pyautogui.keyUp("y")
pyautogui.keyUp("a")
pyautogui.keyUp("s")
thold = time.time()
while time.time() - thold < 0.3:
pyautogui.keyDown('s')
admin()
def start():
pyautogui.keyDown("y")
time.sleep(0.1)
if keyboard.is_pressed("t"):
sys.exit()
def evenfront():
thold = time.time()
thent = time.time()
while time.time() - thold < random.uniform(17.0, 17.3):
#holds down a for 17 sec
pyautogui.keyDown("a")
#does island check every third second
then = time.time() - thent
if then > 3:
island_check()
thent = thent + then
if keyboard.is_pressed("t"):
sys.exit()
def oddback():
thold = time.time()
thent = time.time()
while time.time() - thold < random.uniform(17.0, 17.3):
pyautogui.keyDown("s")
then = time.time() - thent
if then > 3:
island_check()
thent = thent + then
if keyboard.is_pressed("t"):
print("system exit, T pressed")
sys.exit()
def time_check():
then = time.time() - thent
if then > 2:
admin()
thent = thent + then
def admin():
time.sleep(0.5)
pyautogui.press('t')
time.sleep(0.3)
pyautogui.press('?')
pyautogui.press('enter')
time.sleep(1.5)
pyautogui.press('t')
pyautogui.write('hello?', interval=random.uniform(0.1, 0.5))
time.sleep(0.1)
pyautogui.press('enter')
sys.exit()
def macro():
time.sleep(7)
rep = 1
while True:
time.sleep(round(random.uniform(0.1, 0.11), 2))
if rep == 1:
start()
rep = rep + 1
if rep == 2:
evenfront()
rep = rep + 1
pyautogui.keyUp("a")
time.sleep(round(random.uniform(0.11, 0.17), 2))
elif rep == 3:
oddback()
rep = rep - 1
pyautogui.keyUp("s")
time.sleep(round(random.uniform(0.11, 0.17), 2))
while True:
macro()
I have also just tried to do it this way but it does not work either:
def island_check():
if pyautogui.locateOnScreen(r"C:\Users\myname\Desktop\Skyblock_SugarcaneMacro\Island.png", confidence=0.7) == None:
pyautogui.keyUp("y")
pyautogui.keyUp("a")
pyautogui.keyUp("s")
time.sleep(1)
admin()
Related
I made a script to do something in game and it works but it doesn't do anything in the game it types the characters but the game doesn't do anything with that:
import pyautogui as pg
import time
time.sleep(10)
loop_end = time.time() +60 * 10
while time.time() < loop_end:
pg.click(button="Left")
a_loop_end = time.time() +3
while time.time() < a_loop_end:
pg.press("w")
b_loop_end = time.time() +1.5
while time.time() < b_loop_end:
pg.press("a")
c_loop_end = time.time() +3
while time.time() < c_loop_end:
pg.press("s")
d_loop_end = time.time() +1.5
while time.time() < d_loop_end:
pg.press("d")
I'd like to code a bot, that is able to play a game, which is called "piano Tiles". Basically there are four vertical lanes, and there are black tiles falling down in each lane. The player needs to click them before they reach the End of the screen. Its getting faster while playing.
My goal is to get the highest score possible. The world record is currently at 17 clicks/second(tiles/second). I am not able to get any higher than 15 clicks/second but i am just not able to tell where i slow my script down.
My first approach was to check one single pixel/lane with pyautogui.pixel(x,y) and if its rgb value == the color of the tile - click on that position. Score with that variant ~10 clicks/second.
After that i calculated an offset to keep on with the acceleration, basically i added an increasing number to the y position of that click, which left me at arround 12 clicks/second.
I recorded it and watched it fail frame by frame. What happend is, that eventually the game got so fast that the script for an example is not able to detect pixel in "lane 1" while click happens in "lane 4"
The solution, i came up with, is multiprocessing and pypy.
import pyautogui
import multiprocessing
import time
time.sleep(2)
print("READYprint")
def Lane1():
a = 0
b = 0
pyautogui.PAUSE = 0
while True:
if pyautogui.pixel(800, 520) [0] == 0:
pyautogui.click(x=800, y=520 + b)
a = a + 1
b = a // 15
def Lane2():
a = 0
b = 0
pyautogui.PAUSE = 0
while True:
if pyautogui.pixel(902, 520) [0] == 0:
pyautogui.click(x=902, y=520 + b)
a = a + 1
b = a // 15
def Lane3():
a = 0
b = 0
pyautogui.PAUSE = 0
while True:
if pyautogui.pixel(1033, 520) [0] == 0:
pyautogui.click(x=1033, y=520 + b)
a = a + 1
b = a // 15
def Lane4():
a = 0
b = 0
pyautogui.PAUSE = 0
while True:
if pyautogui.pixel(1134, 520) [0] == 0:
pyautogui.click(x=1134, y=520 + b)
a = a + 1
b = a // 15
p1 = multiprocessing.Process(target=Lane1)
p2 = multiprocessing.Process(target=Lane2)
p3 = multiprocessing.Process(target=Lane3)
p4 = multiprocessing.Process(target=Lane4)
if __name__ == "__main__":
p1.start()
p2.start()
p3.start()
p4.start()
i also did run a test, to benchmark the performance of the script.
import time
import pyautogui
start_time = time.time()
def test():
a = 0
b = 0
pyautogui.PAUSE = 0
while a < 100:
if pyautogui.pixel(970, 208) [0] == 255:
pyautogui.click(x=970, y=208 + b)
a = a + 1
b = a // 15
test()
print("--- %s seconds ---" % (time.time() - start_time))
Output: --- 1.7149109840393066 seconds ---, which is for 100 times "get rgb value + click, if its white."
I have no idea why the bot is that "slow" then. When it fails its far away from that 0,017... seconds/checked_click. Could the reason for this be the multiprocessing? While it did get a bit faster, it should have been a lot faster. I also did run it without pypy. Without the pypy JIT its ~13 clicks/second.
Not a direct answer to your question but it might be faster to get a screenshot for all four lanes at once. pyautogui.pixel() combines the screenshot and getpixel functions. So your code gets a screenshot individually for each lane. A faster way might be to do this:
xlocations= [800,902,1033,1134]
yloc=520
while True:
im = pyautogui.screenshot()
for xloc in xlocations:
if im.getpixel((xloc, yloc)) [0] == 0:
pyautogui.click(x=xloc, y=yloc+ b)
a = a + 1
b = a // 15
The "final" solution i came up with was the following:
import time
import win32api, win32con, win32ui
import multiprocessing
time.sleep(1)
print("RDY")
def Lane1():
window_name = "App Player"
wd = win32ui.FindWindow(None, window_name)
while True:
dc = wd.GetWindowDC()
try:
j = dc.GetPixel (35,230)
if j == 0:
win32api.SetCursorPos((35, 230))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
time.sleep(0.01)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
dc.DeleteDC()
except win32ui.error:
print("we got an error 1")
continue
def Lane2():
window_name = "App Player"
wd = win32ui.FindWindow(None, window_name)
while True:
dc = wd.GetWindowDC()
try:
j = dc.GetPixel (60,240)
if j == 0:
win32api.SetCursorPos((60, 240))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
time.sleep(0.01)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
dc.DeleteDC()
except win32ui.error:
print("we got an error 2")
continue
def Lane3():
window_name = "App Player"
wd = win32ui.FindWindow(None, window_name)
while True:
dc = wd.GetWindowDC()
try:
j = dc.GetPixel (120,250)
if j == 0:
win32api.SetCursorPos((120, 250))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
time.sleep(0.01)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
dc.DeleteDC()
except win32ui.error:
print("we got an error 3")
continue
def Lane4():
window_name = "App Player"
wd = win32ui.FindWindow(None, window_name)
while True:
dc = wd.GetWindowDC()
try:
j = dc.GetPixel (180,260)
if j == 0:
win32api.SetCursorPos((180, 260))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
time.sleep(0.01)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
dc.DeleteDC()
except win32ui.error:
print("we got an error 4")
continue
p1 = multiprocessing.Process(target=Lane1)
p2 = multiprocessing.Process(target=Lane2)
p3 = multiprocessing.Process(target=Lane3)
p4 = multiprocessing.Process(target=Lane4)
if __name__ == "__main__":
p1.start()
p2.start()
p3.start()
p4.start()
p1.join()
p2.join()
p3.join()
p4.join()
i checked pixels on different y positions to not have this race condition between the different processes, which did lead to missklicks. Also it helped a lot to keep the game window as small as possible because emulators tend to be laggy.
With this version of the bot the score is about 22 clicks/second.
I am a beginner and am getting this error when I run my code in main_odroid.py:
'NameError: name 'alarmthresh5' is not defined'
When i run this code:
from threading import Thread
def func3():
Import main_odroid
global alarmthresh5
alarmthresh5 = 1.45 * stddev2
[...]
if floats[1] > alarmthresh5:
wpi.digitalWrite(1, 1)
[...]
Thread(target = func3).start()
[...]
[...] means the rest of the (irrelevant) code that I excluded for clarity.
I used the search function and tried different answers but it did not solve the problem.
Thanks I and I am interested in your answers.
EDIT: scope of variable alarmthresh5 is global i think, because I typed 'global alarmthresh5' in func3.
EDIT2: The entire code
import subprocess
from subprocess import Popen, PIPE
import os
import odroid_wiringpi as wpi
from collections import deque
import time
import datetime
from threading import Thread
from math import sqrt
sysdamping = 10
freqdamping = 14
totalbins = 2000
#Functions
def average(p): return sum(p) / float(len(p))
def variance(p): return list(map(lambda x: (x - average(p))**2, p))
def std_dev(p): return sqrt(average(variance(p)))
wpi.wiringPiSetup()
wpi.pinMode(1, 1)
wpi.pinMode(5, 1)
wpi.pinMode(27, 1)
wpi.pinMode(31, 1)
wpi.pinMode(23, 1)
wpi.pinMode(11, 1)
wpi.digitalWrite(23, 0)
wpi.digitalWrite(11, 0)
wpi.pinMode(2, 1)
wpi.pinMode(7, 1)
wpi.digitalWrite(2, 0)
wpi.digitalWrite(7, 0)
wpi.pinMode(9, 1)
wpi.digitalWrite(9, 0)
time.sleep(0.1)
wpi.pullUpDnControl(30, 2)
os.system("killall -9 soapy_power -q")
time.sleep(0.1)
def func2():
exec(open("/home/odroid/rtl-power-fftw/build/deactiveer.py").read())
def func3():
import main_odroid
global alarmthresh1
global alarmthresh2
global alarmthresh3
global alarmthresh4
global alarmthresh5
global Lijst
alarmthresh1 = (average(rolling[i]) + 1.45 * stddev2)
alarmthresh2 = alarmthresh1 + 2
alarmthresh3 = alarmthresh2 + 2
alarmthresh4 = alarmthresh3 + 2
alarmthresh5 = alarmthresh4 + 2
Lijst = [381843000.0, 382242000.0, 382245000.0, 382248000.0, 382254000.0, 382257000.0, 382305000.0, 382308000.0, 382320000.0, 382323000.0, 382326000.0, 382389000.0, 382392000.0, 382557000.0, 382560000.0, 382671000.0, 383157000.0, 383454000.0, 383457000.0, 383469000.0, 383472000.0, 383997000.0, 384000000.0, 384003000.0, 384006000.0]
def func4():
import main_odroid
global stddev2
stddev2 = std_dev(sweep)
def func1():
cmd = ["/home/odroid/.local/bin/soapy_power", "-f", "433M", "-r", "6M", "--force-rate", "-q", "-c", "-b", "2000", "-F", "rtl_power_fftw"]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)
rolling = []
i = 0
rolling_avg = deque([])
sweep = deque([], maxlen=1500)
stddev = 12
totalbins = 2000
# Let's see what's going on with rtl_power_fftw
for line in iter(p.stdout.readline, b''):
#Ignore garbage output
if not (b'#' in line or not line.strip()):
floats = list(map(float, line.split()))
# Create 2D array
if len(rolling) < totalbins:
rolling.append(deque([]))
rolling[i].append(floats[1])
sweep.append(floats[1])
# Let's start filtering...
if len(rolling[i]) >= freqdamping:
rolling[i].popleft()
print("ref 5")
input_state3 = wpi.digitalRead(9)
if floats[1] > alarmthresh5 and 380820000.0 < floats[0] < 384570000.0 and floats[0] not in Lijst: # Led 5
wpi.digitalWrite(1, 1)
if input_state3 == 0:
wpi.digitalWrite(9, 1) # Buzzer proxy
wpi.digitalWrite(31, 1) # Buzzer ON
print(round(floats[0]), round(floats[1]), alarmthresh5, "ref2")
Thread(target = func2).start()
if floats[1] > alarmthresh1 and floats[0] in [380310000.0, 381444000.0, 381579000.0, 381780000.0, 381783000.0, 382110000.0, 382836000.0, 382881000.0, 382884000.0, 382887000.0, 382890000.0, 382893000.0, 383037000.0, 383085000.0, 383340000.0, 383460000.0, 384258000.0, 384261000.0, 384264000.0]:
if input_state3 == 0:
wpi.digitalWrite(9, 1) # Buzzer proxy
wpi.digitalWrite(31, 1) # Buzzer ON
print(round(floats[0]), round(floats[1]), alarmthresh1, "ref1")
Thread(target = func2).start()
if floats[1] > alarmthresh4 and 380820000.0 < floats[0] < 384570000.0 and floats[0] not in Lijst: # Led 4
wpi.digitalWrite(7, 1)
if floats[1] > alarmthresh3 and 380820000.0 < floats[0] < 384570000.0 and floats[0] not in Lijst: # Led 3
wpi.digitalWrite(23, 1)
if floats[1] > alarmthresh2 and 380820000.0 < floats[0] < 384570000.0 and floats[0] not in Lijst: # Led 2
wpi.digitalWrite(5, 1)
if floats[1] > alarmthresh1 and 380820000.0 < floats[0] < 384570000.0 and floats[0] not in Lijst: # Led 1
input_state = wpi.digitalRead(27)
if input_state == 0:
wpi.digitalWrite(27, 1)
Thread(target = func2).start()
# Increment or reset indexer (i)
if i < totalbins - i: i = i + 1
else:
i = 0
Thread(target = func4).start() # Set stddev2
Thread(target = func3).start() # Set alarmthresh1 - alarmthresh5
print("ref 6")
p.stdout.close()
p.wait()
Thread(target = func1).start()
Ref 6 prints before ref 5, so func3 is started before alarmthresh5 is called.
Can you specify scope of variable alarmthresh5. Try to add variable in function definition only, something like this: def func3(alarmthresh5=valueyouwantotput)
I want to print list data on the specific delays which are on another list. I Want to loop this process for a specific time, but I'm unable to implement it in a thread.
from time import sleep
import datetime
now = datetime.datetime.now()
Start_Time = datetime.datetime.now()
Str_time = Start_Time.strftime("%H:%M:%S")
End_Time = '11:15:00'
class sampleTest:
#staticmethod
def test():
list1 = ["Hello", "Hi", "Ola"]
list2 = [5, 10, 7]
# print(f"{data} delay {delay} & time is {t} ")
# sleep(delay)
i = 0
while i < len(list1):
t = datetime.datetime.now().strftime('%H:%M:%S')
print(f"{list1[i]} delay {list2[i]} & time is {t} ")
sleep(list2[i])
i += 1
else:
print("All Data is printed")
if __name__ == '__main__':
obj = sampleTest
while Str_time < End_Time:
obj.test()
Str_time = datetime.datetime.now().strftime("%H:%M:%S")
else:
print("Time Is done")
Expected output: On first, loop it should print all list data but in the second loop, it should run as per the delay.
1st time: Hello, Hi, Ola
after that
1. Every 5 seconds it should print Hello
2. Every 10 seconds it should print Hi
3. Every 7seconds it should print Ola
Actual Output: List of data is getting printed as per the delay.
Hello delay 5 & time is 11:41:45
Hi delay 10 & time is 11:41:50
Ola delay 3 & time is 11:42:00
All Data is printed
Hello delay 5 & time is 11:42:03
Hi delay 10 & time is 11:42:08
Ola delay 3 & time is 11:42:18
You can try comparing the current time with the start time, for example:
time.sleep(1);
diff = int(time.time() - start_time)
if (diff % wait_time == 0):
print(text_to_print)
Here is the full code implementing this:
from time import sleep
import time
import datetime
now = datetime.datetime.now()
Start_Time = datetime.datetime.now()
Str_time = Start_Time.strftime("%H:%M:%S")
End_Time = '11:15:00'
starttime=time.time()
diff = 0
class sampleTest:
#staticmethod
def test():
list1 = ["Hello", "Hi", "Ola"]
list2 = [5, 10, 7]
for i in range(len(list1)):
if (diff % list2[i] == 0):
t = datetime.datetime.now().strftime('%H:%M:%S')
print(f"{list1[i]} delay {list2[i]} & time is {t} ")
if __name__ == '__main__':
obj = sampleTest
while Str_time < End_Time:
obj.test()
time.sleep(1);
diff = int(time.time() - starttime)
Str_time = datetime.datetime.now().strftime("%H:%M:%S")
else:
print("Time Is done")
In accordance with your desired output, I believe threads are the best option, which means:
from time import sleep
import datetime
import threading
now = datetime.datetime.now()
Start_Time = datetime.datetime.now()
Str_time = Start_Time.strftime("%H:%M:%S")
End_Time = '11:15:00'
class sampleTest:
def __init__(self):
self.run = True
print ("1st time: Hello, Hi, Ola")
print ("Now: " + datetime.datetime.now().strftime('%H:%M:%S'))
def test(self, i):
list1 = ["Hello", "Hi", "Ola"]
list2 = [5, 10, 7]
while self.run:
sleep(list2[i])
t = datetime.datetime.now().strftime('%H:%M:%S')
print(f"{list1[i]} delay {list2[i]} & time is {t}")
def stop(self):
self.run = False
if __name__ == '__main__':
obj = sampleTest()
t1 = threading.Thread(target=obj.test,args=(0,))
t2 = threading.Thread(target=obj.test,args=(1,))
t3 = threading.Thread(target=obj.test,args=(2,))
t1.start()
t2.start()
t3.start()
while Str_time < End_Time:
Str_time = datetime.datetime.now().strftime("%H:%M:%S")
else:
obj.stop()
t1.join()
t2.join()
t3.join()
print("All data is printed")
print("Time Is done")
I'm trying to create a simple game where the point is to collect as many blocks as you can in a certain amount of time, say 10 seconds. How can I get a timer to begin ticking at the start of the program and when it reaches 10 seconds, do something (in this case, exit a loop)?
import time
now = time.time()
future = now + 10
while time.time() < future:
# do stuff
pass
Alternatively, if you've already got your loop:
while True:
if time.time() > future:
break
# do other stuff
This method works well with pygame, since it pretty much requires you to have a big main loop.
Using time.time()/datetime.datetime.now() will break if the system time is changed (the user changes the time, it is corrected by a timesyncing services such as NTP or switching from/to dayligt saving time!).
time.monotonic() or time.perf_counter() seems to be the correct way to go, however they are only available from python 3.3. Another possibility is using threading.Timer. Whether or not this is more reliable than time.time() and friends depends on the internal implementation. Also note that creating a new thread is not completely free in terms of system resources, so this might be a bad choice in cases where a lot of timers has to be run in parallel.
I use this function in my python programs. The input for the function is as example:
value = time.time()
def stopWatch(value):
'''From seconds to Days;Hours:Minutes;Seconds'''
valueD = (((value/365)/24)/60)
Days = int (valueD)
valueH = (valueD-Days)*365
Hours = int(valueH)
valueM = (valueH - Hours)*24
Minutes = int(valueM)
valueS = (valueM - Minutes)*60
Seconds = int(valueS)
print Days,";",Hours,":",Minutes,";",Seconds
start = time.time() # What in other posts is described is
***your code HERE***
end = time.time()
stopWatch(end-start) #Use then my code
The threading.Timer object (documentation) can count the ten seconds, then get it to set an Event flag indicating that the loop should exit.
The documentation indicates that the timing might not be exact - you'd have to test whether it's accurate enough for your game.
In this example the loop is run every second for ten seconds:
import datetime, time
then = datetime.datetime.now() + datetime.timedelta(seconds=10)
while then > datetime.datetime.now():
print 'sleeping'
time.sleep(1)
For a StopWatch helper class, here is my solution which gives you precision on output and also access to the raw start time:
class StopWatch:
def __init__(self):
self.start()
def start(self):
self._startTime = time.time()
def getStartTime(self):
return self._startTime
def elapsed(self, prec=3):
prec = 3 if prec is None or not isinstance(prec, (int, long)) else prec
diff= time.time() - self._startTime
return round(diff, prec)
def round(n, p=0):
m = 10 ** p
return math.floor(n * m + 0.5) / m
Asks you when to stop [seconds]
Adds '0' at starting [1-9]
import time
import sys
stop = int(input('> '))
second = 0
print('> Stopwatch Started.')
while stop > second:
if second < 9:
second = second + 1
time.sleep(1)
sys.stdout.write('\r> ' + '0' + str(second))
else:
second += 1
time.sleep(1)
sys.stdout.write('\r' + '> ' + str(second))
print('\n> Stopwatch Stopped.')
As a learning exercise for myself, I created a class to be able to create several stopwatch timer instances that you might find useful (I'm sure there are better/simpler versions around in the time modules or similar)
import time as tm
class Watch:
count = 0
description = "Stopwatch class object (default description)"
author = "Author not yet set"
name = "not defined"
instances = []
def __init__(self,name="not defined"):
self.name = name
self.elapsed = 0.
self.mode = 'init'
self.starttime = 0.
self.created = tm.strftime("%Y-%m-%d %H:%M:%S", tm.gmtime())
Watch.count += 1
def __call__(self):
if self.mode == 'running':
return tm.time() - self.starttime
elif self.mode == 'stopped':
return self.elapsed
else:
return 0.
def display(self):
if self.mode == 'running':
self.elapsed = tm.time() - self.starttime
elif self.mode == 'init':
self.elapsed = 0.
elif self.mode == 'stopped':
pass
else:
pass
print "Name: ", self.name
print "Address: ", self
print "Created: ", self.created
print "Start-time: ", self.starttime
print "Mode: ", self.mode
print "Elapsed: ", self.elapsed
print "Description:", self.description
print "Author: ", self.author
def start(self):
if self.mode == 'running':
self.starttime = tm.time()
self.elapsed = tm.time() - self.starttime
elif self.mode == 'init':
self.starttime = tm.time()
self.mode = 'running'
self.elapsed = 0.
elif self.mode == 'stopped':
self.mode = 'running'
#self.elapsed = self.elapsed + tm.time() - self.starttime
self.starttime = tm.time() - self.elapsed
else:
pass
return
def stop(self):
if self.mode == 'running':
self.mode = 'stopped'
self.elapsed = tm.time() - self.starttime
elif self.mode == 'init':
self.mode = 'stopped'
self.elapsed = 0.
elif self.mode == 'stopped':
pass
else:
pass
return self.elapsed
def lap(self):
if self.mode == 'running':
self.elapsed = tm.time() - self.starttime
elif self.mode == 'init':
self.elapsed = 0.
elif self.mode == 'stopped':
pass
else:
pass
return self.elapsed
def reset(self):
self.starttime=0.
self.elapsed=0.
self.mode='init'
return self.elapsed
def WatchList():
return [i for i,j in zip(globals().keys(),globals().values()) if '__main__.Watch instance' in str(j)]
This is the Shortest Way I know of doing it:
def stopWatch():
import time
a = 0
hours = 0
while a < 1:
for minutes in range(0, 60):
for seconds in range(0, 60):
time.sleep(1)
print(hours,":", minutes,":", seconds)
hours = hours + 1
New to the python world!
I need a System Time independent Stopwatch so I did translate my old C++ class into Python:
from ctypes.wintypes import DWORD
import win32api
import datetime
class Stopwatch:
def __init__(self):
self.Restart()
def Restart(self):
self.__ulStartTicks = DWORD(win32api.GetTickCount()).value
def ElapsedMilliSecs(self):
return DWORD(DWORD(win32api.GetTickCount()).value-DWORD(self.__ulStartTicks).value).value
def ElapsedTime(self):
return datetime.timedelta(milliseconds=self.ElapsedMilliSecs())
This has no 49 days run over issue due to DWORD math but NOTICE that GetTickCount has about 15 milliseconds granularity so do not use this class if your need 1-100 milliseconds elapsed time ranges.
Any improvement or feedback is welcome!