im currently learning Python(about 3 months expirience now) and wanted to try out the module "Mouse", ive built a simple autoclicker script(not using it in game) but for values above 12(cps) it reaches below targeted cps, i suspect this is because of the if loops in my program, could anybody help me make this more efficient?
Code here:
import mouse
import keyboard
import time
staat = 0
cps = input("Typ de hoeveelheid cps die je wilt in.")
cps = float(cps)
cps = 1 / cps
print("pauzeer de loop door op / te drukken")
while True:
if staat == 1:
mouse.click('left')
if keyboard.is_pressed('/'):
if staat == 0:
staat = 1
else:
staat = 0
time.sleep(cps)
Thanks in advance
Using 1 instead of True is slightly faster. Importing this way is slightly faster and calling without the '.' is also slightly faster. If still not fast enough I could implement multi-threading .
from mouse import click
from keyboard import is_pressed
from time import sleep,perf_counter
staat = 0
cps = input("Typ de hoeveelheid cps die je wilt in.")
cps = float(cps)
cps = 1 / cps
print("pauzeer de loop door op / te drukken")
while 1:
timeing = perf_counter()
if staat:
click('left')
if is_pressed('/'):
if not staat:
staat = 1
else:
staat = 0
sleep(cps - (perf_counter() - timeing)
Related
I have a good working function. Pretty long but starts with:
from timer import timer
#timer
def Klasse3():
while True:
jaar = input('Welk jaar wil je zien: ')
try:
jaar = int(jaar)
except ValueError:
print ('Er ging iets mis: het lijkt er op dat je geen jaartal invoerde.')
continue
if 2017 <= jaar < 2020:
print(f'{jaar} is beschikbaar in de database. Een klein moment geduld a.u.b.')
print('Processing request......')
break
else:
print ('Helaas, alleen de jaren 2017,2018 en 2019 zijn beschikbaar.')
etc., etc., etc., which means a lot of code in the middle part and then the finish(first print seems to be out of place (no idea why) but is in script in correct place:
print(f'In {jaar} waren er {abs(df_verschil_dag)} {meer_minder_dag} dagopnames dan in {prev_jaar}.')
print(f'In {jaar} waren er {abs(df_verschil_kort)} {meer_minder_kort} kortdurende opnames dan in {prev_jaar}.')
print(f'In {jaar} waren er {abs(df_verschil_middel)} {meer_minder_middel} middellange opnames dan in {prev_jaar}.')
print(f'In {jaar} waren er {abs(df_verschil_lang)} {meer_minder_lang} langdurige opnames dan in {prev_jaar}.')
print()
print('onderstaand de grafische weergave van wat u hierboven las:')
#groupby resultaat van multi index naar enkel df omzetten
val_cnt3 = val_cnt3.reset_index(name='Totaal')
#kolom met jaar toevoegen
val_cnt3['jaar'] = jaar
#groupby resultaat van multi index naar enkel df omzetten
val_cnt_prev = val_cnt_prev.reset_index(name='Totaal')
#kolom met jaar toevoegen aan voorgaande jaar overzicht
val_cnt_prev['jaar'] = prev_jaar
#beide df's jaar en prev_jaar samenvoegen met concat
frames = [val_cnt3,val_cnt_prev]
result = pd.concat(frames, ignore_index=True)
result.columns=('type', 'totaal', 'jaar')
sns.catplot(x="type", y="totaal", hue='jaar', kind="bar", data=result)
As can be seen in the beginning I use a decorator: #timer:
import sys
import time
import functools
def timer(func):
"""Print the runtime of the decorated function"""
#functools.wraps(func)
def wrapper_timer(*args, **kwargs):
start_time = time.perf_counter() # 1
value = func(*args, **kwargs)
end_time = time.perf_counter() # 2
run_time = end_time - start_time # 3
print(f"Deze functie nam {run_time:.2f} seconden in beslag.")
print('Dank u wel voor het gebruiken van onze online analyse tool. Graag tot een volgende keer.')
return value
return wrapper_timer
Function and decorator work well. No problem in functionality. But..... the seaborn plot (works well as well) is printed after the final prints in my timer decorator. And that is strange, not supposed too.
The function should run (inside Timer decorator) and after finishing the complete function, the Timer decorator should print: this function took .... secs and the thank you print.
But instead the final part of Timer function is printed before the SNS plot as can be seen underneath.
What can I do (Jupiter Notebook) to get the sns plot printed in the right place? So, the sentence with seconds and the thank you (dank u wel etc. in Dutch) gets printed after the plot?
Deze functie nam 14.08 seconden in beslag.
Dank u wel voor het gebruiken van onze online analyse tool. Graag tot een volgende keer.
matplotlib figures are displayed in a separate thread. Most graphics packages do drawing like that. The timer and printouts in the main thread are not affected by the processing of the display thread.
I need help with this exercise please. I have to ask the user if want to set an alarm, either for a specific date or for certain days of the week. In addition to printing the time adding 1 and I have to say if it is day or night (This last part of the code was made by the teacher of the course, I did all the alarm).
The code should open a .txt file but it does not, I have run the code several times and checked the Pycharm but nothing. Here it is
from time import sleep
import datetime
NIGHT_STARTS = 19
DAY_STARTS = 8
HOUR_DURATION = 1
def write_file_and_screen(text, file_name):
with open(file_name, "a+") as file_text:
file_text.write("{}{}".format(text, "\n"))
print(text)
def week_date_to_day(day):
days_list = {0: "Monday", 1: "Tuesday", 2: "Wednesday", 3: "Thursday", 4: "Friday", 5: "Saturday",
6: "Sunday"}
day_weekday = day.weekday
if day_weekday == days_list.keys():
week_day_of_the_day = days_list.get(day_weekday)
return week_day_of_the_day
def main():
today = datetime.date.today()
current_time = datetime.datetime.now()
is_night = False
want_alarm = input("Do you want to set a alarm? Yes/No ")
if want_alarm == "Yes":
# Aquí preguntamos si desea una alarma para una fecha específica.
specific_date = input("Do you want an alarm in a specific date? Yes/No ")
if specific_date == "Yes":
date_user = input("Tell me the date. (dd/mm/yyyy) ")
date_format = datetime.datetime.strptime(date_user, "%d/%m/%Y")
if datetime.date.today() == date_format:
write_file_and_screen("ALARM. It's {}".format(date_format), "Specific alarm.txt")
print("ALARM. It's {}".format(date_format))
elif specific_date == "No":
# Aquí preguntamos si desea una alarma normal, haciendo que elija el día y la hora.
normal_alarm = input("Do you want a normal alarm? Yes/No ")
if normal_alarm == "Yes":
hour_alarm = int(input("Hour of the alarm? 0/23 "))
datetime.time(hour=hour_alarm)
days_of_alarm_input = ""
days_of_alarm_list = []
print("Write End to end the loop ")
while not days_of_alarm_input == "End":
days_of_alarm_input = input("Tell me the days that you want to set the alarm 0 to 6, 0 is "
"Monday ""and 6 is Sunday ")
days_of_alarm_list.append(days_of_alarm_input)
if days_of_alarm_input == "End":
for i in days_of_alarm_list:
if today.weekday() == days_of_alarm_list:
write_file_and_screen("ALARM. It's {}".format(week_date_to_day(today)), "Weekdays "
"alarm.txt")
while True: # Se imprime la hora actual y se le va sumando una más, además de que si indica si es de día
# o de noche
sleep(HOUR_DURATION)
current_time += datetime.timedelta(hours=1)
light_changed = False
if (current_time.hour >= NIGHT_STARTS or current_time.hour <= DAY_STARTS) and not is_night:
is_night = True
light_changed = True
elif (DAY_STARTS < current_time.hour < NIGHT_STARTS) and is_night:
is_night = False
light_changed = True
if light_changed:
if is_night:
write_file_and_screen("It's night", "hours.txt")
else:
write_file_and_screen("It's day", "hours.txt")
write_file_and_screen("The hour is {}".format(current_time), "horas.txt")
sleep(2)
if __name__ == "__main__":
main()
When I run the program and I enter the necessary data for the alarm, simply the program goes to the 3rd part of the code and starts printing the time and adding 1 without opening the .txt file:
The hour is 2019-11-09 19:50:51.614472
The hour is 2019-11-09 20:50:51.614472
The hour is 2019-11-09 21:50:51.614472
The hour is 2019-11-09 22:50:51.614472
The hour is 2019-11-09 23:50:51.614472
The hour is 2019-11-10 00:50:51.614472
The hour is 2019-11-10 01:50:51.614472
The hour is 2019-11-10 02:50:51.614472
The hour is 2019-11-10 03:50:51.614472
The hour is 2019-11-10 04:50:51.614472
The hour is 2019-11-10 05:50:51.614472
If you need to know something else or If I did not explain myself well please tell me. (Sorry for my English)
Update:
The specific date alarm works! Thanks!
but there is another problem. The "normal alarm" does not. When the program is on the line for i in days_of_alarm_list: it skip it to while True
i = 6 , it suppose to pass the for i in days_of_alarm_list:
But the program passes to while True
There was a type mismatch earlier, that's why you were going to the third part every time.
datetime.datetime.strptime('10/11/2019',"%d/%m/%Y") returns
'datetime.datetime(2019, 11, 10, 0, 0)'
datetime.date.today() returns 'datetime.date(2019, 11, 10)'
replace your if condition with the following line:
if datetime.date.today() == date_format.date() :
Your code working fine, I tested it on my machine,
In your code you'r sleeping your condition for 1 hour every time, that's why your code taking more time for execute file creation, modification.
Exactly waiting for 1 Hour every time when while condition looping
sleep method is
sleep(HOUR_DURATION)
You can check it by changing the time duration from sleep(HOUR_DURATION) to sleep(5)
Your condition will sleep just for five milliseconds
Happy codding
I am implement a simple simulator of soccer with python using threads and lock, the app works fine but I have doubts in the way that implement the thread it seems to me that the first team has an advantage because is executing first.
def jugar(Equipo1, Equipo2):
# Busco las probabilidades de encajar por cada equipo
prob_encajar_eq1 = Equipo1.probabilidad_encajar()
prob_encajar_eq2 = Equipo2.probabilidad_encajar()
def jugar_equipo1(defensa_rival):
semaforo.acquire()
if Equipo1.hacer_pases():
Equipo1.shoot(defensa_rival)
semaforo.release()
def jugar_equipo2(defensa_rival):
semaforo.acquire()
if Equipo2.hacer_pases():
Equipo2.shoot(defensa_rival)
semaforo.release()
hilo_equipo1 = threading.Thread(name = 'hilo_eq1', target = jugar_equipo1, args = (prob_encajar_eq2,))
hilo_equipo2 = threading.Thread(name = 'hilo_eq2', target = jugar_equipo2, args = (prob_encajar_eq1,))
hilo_equipo1.start()
hilo_equipo2.start()
hilo_equipo1.join()
hilo_equipo2.join()
to make several attempts both teams, I do a cicle for a few seconds and inside the function jugar() which is the one that does the work with threads but here is were I have the doubts, because every time that jugar is executing the threads are declared again.
if __name__ == '__main__':
cargar_informacion()
eqA = Equipo(equipoA, ranking_eqA)
eqB = Equipo(equipoB, ranking_eqB)
probabilidades = porcenajes_ranking(ranking_eqA)
eqA.cargar_probabilidades(probabilidades)
probabilidades = porcenajes_ranking(ranking_eqB)
eqB.cargar_probabilidades(probabilidades)
starttime=time.time()
tiempo = 0
# creo la barra de progreso
bar = progressbar.ProgressBar(widgets=[
progressbar.Percentage(),
progressbar.Bar(),
], max_value=100).start()
# hacemos que el juego tarde aproximadamente 10seg en simularse.
while tiempo < 10:
time.sleep(0.3 - ((time.time() - starttime) % 0.3))
jugar(eqA,eqB)
tiempo = time.time() - starttime
bar += 2.8
bar.finish() # Para que finalice la barra de progreso
resultados_finales(eqA, eqB) # Mostramos el resultado final del partido.
I have a Problem. I am learning Python i get a EOL Error. I searching for a solution but i find nothing.
def gefangen(mx,my):
if not geschafft:
paula.write('Super, du hast Paula erwischt!')
else:
paula.write('Das zählt ja wohl nicht?!')
onclick(start) # Mauskoordinaten werden
paula.onclick(gefangen) # automatisch übergeben
while paula.distance(horst) > 4:
horst.fd(randint(3,7))
horst.lt(randint(-20,40)/10)
paula.setheading(paula.towards(horst))
paula.fd(randint(1,10))
if count % 20 == 0:
horst.stamp()
paula.stamp()
count += 1
if horst.ycor()<-260 or horst.xcor()>310:
horst.write('Puh, geschafft!')
paula.write('Mist, entwischt!')
geschafft=True
break
if not geschafft:
horst.write("Erwischt!",font=("Arial",14,"bold")")
pu()
goto(-200,-200)
shape("circle")
write("Noch einmal? Hier klicken")
pd()
st()
http://prntscr.com/gstq0d i get this error (look screenshot)
It looks like you have an extra double quote at "bold")") ...
if not geschafft:
horst.write("Erwischt!",font=("Arial",14,"bold")")
horst.write("Erwischt!",font=("Arial",14,"bold")")
In this line, You have given an extra double quotes at the end.
I'm working on the implementation of several algorithms to compute shortest paths on graphs.
I have managed to implement Dijkstra's algorithm sequentially and I'm now trying to optimize my algorithm through the multiprocessing module of Python.
As a whole the code works. What I am trying to do here is :
First to check how many cpus I can work on with nb_cpu = mp.cpu_count()
Then dividing all the nodes I have in my graph accordingly
Finally calling the method subprocess_dijkstra that should compute the dijkstra algorithm for each of the nodes it is given as an argument (the idea being that each process only has to compute the algorithm for a smaller part of the graph).
When I run my script (called from a main.py file where I just format the data to suit my needs), I have 4 processes launched as I should.
However, they do not seem to execute the for node in nodes loop defined in subprocess_dijkstra.
Each process only computes the code once and then they go on hold indefinitely...
It is my first attempt at multiprocessing under Python so I may have missed a detail. Does anybody have an idea ?
When I interrupt the script, python tells me that the interruption takes place on the p.join() line.
Thanks to anyone helping me :)
Here is my code :
import multiprocessing as mp
def subprocess_dijkstra(do_print, nodes, tab_contenu, tab_distances):
tab_dist_initial = dict(tab_distances)
tab_dist = dict()
for node in nodes:
visited_nodes = list()
tab_dist = dict(tab_dist_initial)
dmin = -1
resultat = ""
filename = "dijkstra"+str(node)+".txt"
if do_print:
dt = open(filename, 'w')
tab_dist[node] = 0
"""Ligne de résultat initiale"""
for valeur in tab_dist.values():
resultat += str(valeur)
resultat += " "
resultat += "\n"
dt.write(resultat)
while len(visited_nodes) != len(tab_contenu):
""" On se place sur le noeud non visité qui a la distance minimale de notre départ """
for cle, valeur in tab_dist.items():
if cle not in visited_nodes:
if dmin ==-1 or valeur<dmin:
dmin = valeur
node = cle
""" On vérifie que le noeud n'a pas déjà été visité """
if (node not in visited_nodes):
""" On regarde les fils de ce noeud et la longueur des arcs"""
for cle,valeur in tab_contenu[node].items():
tab_dist[cle] = min(tab_dist[cle], tab_dist[node]+valeur)
visited_nodes.append(node)
if do_print:
resultat = ""
""" Ligne de résultat """
for valeur in tab_dist.values():
resultat += str(valeur)
resultat += " "
resultat += "\n"
dt.write(resultat)
if do_print:
dt.close()
def main(do_print,donnees):
tab_contenu = donnees[1]
nb_nodes = int(donnees[0])
tab_distances = {x: float('inf') for x in range(nb_nodes)}
args=[(do_print, x, tab_contenu, tab_distances) for x in range(nb_nodes)]
nb_cpu = mp.cpu_count()
pool = mp.Pool(processes = nb_cpu)
pool.starmap(subprocess_dijkstra, args)
pool.close()
pool.join()
I have found the source of my problems.
The tab_dist[node] = 0 was misplaced and should have been put before the if do_print: statement.
All is now working.