Python: Initiate a variable once in a program running every few minutes - python

I have a program running every minutes. I want that when I'm executing it for the first time I do something and after something else; like this :
def alarm_function (alarm):
first_time=0
if first_time==0:
send_on_website(message)
first_time+=1
alarm=0
else:
send_on_website(a_different_message)
if alarm==0:
#do nothing
if alarm==1:
alarm+=1
#do something
So basically after I executed once I want to erase the first line "first_time=0" because I don't want to initiate it again. Also, I want to make a counter on alarm variable which is initiate somewhere in the program. How can I do that ?

you would have to define a new function if you dont want the first_time any more. and for the counter you can put at the top of your program import time and where ever you want the counter to be you use time.sleep(?) #change ? for a any number of seconds

Related

Only run function it is not already running

I need to make on auto clicker that, when the mouse is clicked once (using the 'mouse' module), presses another 5 times. However, I also need to make sure that only the clicks done by the user activate it. Currently (because I don't need an unstoppable mouse as I've already had), it only prints "clicking". This is what I have so far.
jack = 0
import keyboard
import mouse
import sys
from time import sleep
def spamClick(f, jeff):
if jeff <= 0:
jeff = jeff+1
for i in range(f):
#mouse.click()
print ("Clicking")
sleep(0.1)
jeff = 0
mouse.on_click(spamClick, args=(5, jack))
#keyboard.add_hotkey('ctrl+g', spamClick)
keyboard.add_hotkey('ctrl+#', mouse.unhook_all)
keyboard.add_hotkey('ctrl+#', sys.exit)
Thank you in advance.
An easy fix for this is having a top level variable keeping track of the state.
The issue is that you have a function that does an action that starts itself again.
It's functionally the same as
def examplecode():
print("Do stuff")
examplecode()
This is the same as an infinite loop, in your case even worse because you call the function multiple times every time (5 times per action).
So your options to prevent that are as follows:
Have two different ways of clicks, one that triggers the "onclick" event, and one that doesn't.
Use a helper function that keeps track of the "state" of your program. Instead of calling "spamClick()" as your onclick event add the following to your program:
A top level variable that is True when you want it to accept clicks: isUser=True
A function you call instead of "spamclick" that checks the state of the global Var and only then triggers the code:
def examplefunc(num,var):
if isUser:
isUser=False
spamClick(num,var)
isUser=True
I still don't get how your program just "clicks endlessly" instead of crashing due to hitting max recursion depth, but this should work (while being very hacky)
Edit: You should use better naming for variables instead of "jeff", it will make your life worse if you don't down the line. For example "isUser" indicates that it's a boolean (because "isWhatever" indicates it holds a state as a boolean) and states if the input is by a user. Alternatively you could use isFunctionRunning=False that states if the function is on. You would have to switch all the True and False assignments in my example of course to still make sense.

How do I make a countdown timer in Python without importing time?

I'm creating a countdown timer for a game in Python. My problem is I could only find code that uses time.sleep(), which pauses the entire code. Is there a way to make a countdown timer, for example, from 60 seconds. Is it possible to use millis()?
time.sleep() makes your program wait some time and not do anything.
The way it's usually done is to use something like time.time() to get the current time and as your title says: 'count down' from there using your loop and getting the difference between the start value and the current value of time.time(). If it's greater than your desired value, then just simply break out of the loop.
Assuming you have a game loop that runs every tick of your program, you could have a Countdown class whose countdownElapsed function gets called every tick of your game loop and that checks when your countdown is at zero
// Pseudo-code
func countdownElapsed(countdown):
return (countdown.lastTime - time.currentTime()) < 0
You could also create a Scheduler class that stores a bunch of function pointers, their arguments and the time you want to call said function pointers inside a vector of some sort and does the check above for every function inside the vector every tick.
Finally, you can also just have a separate thread where you sleep and time-sensitive tasks.

How to keep a While True loop running with raw_input() if inputs are seldom?

I'm currently working on a project where I need to send data via Serial persistently but need to occasionally change that data based in new inputs. My issue is that my current loop only functions exactly when a new input is offered by raw_input(). Nothing runs again until another raw_input() is received.
My current (very slimmed down) loop looks like this:
while True:
foo = raw_input()
print(foo)
I would like for the latest values to be printed (or passed to another function) constantly regardless of how often changes occur.
Any help is appreciated.
The select (or in Python 3.4+, selectors) module can allow you to solve this without threading, while still performing periodic updates.
Basically, you just write the normal loop but use select to determine if new input is available, and if so, grab it:
import select
while True:
# Polls for availability of data on stdin without blocking
if select.select((sys.stdin,), (), (), 0)[0]:
foo = raw_input()
print(foo)
As written, this would print far more than you probably want; you could either time.sleep after each print, or change the timeout argument to select.select to something other than 0; if you make it 1 for instance, then you'll update immediately when new data is available, otherwise, you'll wait a second before giving up and printing the old data again.
How will you type in your data at the same time while data is being printed?
However, you can use multithreading if you make sure your source of data doesn't interfere with your output of data.
import thread
def give_output():
while True:
pass # output stuff here
def get_input():
while True:
pass # get input here
thread.start_new_thread(give_output, ())
thread.start_new_thread(get_input, ())
Your source of data could be another program. You could connect them using a file or a socket.

Python: Accept user input at any time

I am creating a unit that will do a number of things, one of them counting cycles of a machine. While I will be transferring this over to ladder logic (CoDeSys), I am putting my ideas into Python first.
I will have a count running, with just a simple
counter += 1
print("counter")
to keep track of what cycle I'm on. However, I want to be able to reset this count at any time, preferably by typing "RESET" I understand how to use the input command,
check = input()
however, I do not know how to let the program run while it is searching for an input, or whether or not this is possible at all. Thank you in advance for any answer.
If it helps to understand, here is the code. The big gap is where the problem is. http://pastebin.com/TZDsa4U4
If you only want to signal a reset of the counter, you can catch KeyboardInterrupt exception.
while True:
counter = 0
try:
while True:
counter += 1
print("counter")
except KeyboardInterrupt:
pass

End a Python function after a certain time?

For example, I have this function:
some_global_varible = ""
def bob(some_argument, some_more):
import time
for x in range(10):
print("Working")
time.sleep(1)
return "I finished and this is my result"
How can I run this function for certain amount of time, and if it's not finish in the time end it. But also if it finish get the output of the return (if the is one, because maybe there is none and it simply end).
Also this won't be run in Unix, because I had see some example for Unix that don't work in Windows. Also if you could change the global variable form inside the function it would be perfect, but that as a extra.
First the rest and if it possible (If it not possible to detect an end without the return it doesn't matter, I can include a return just fro that. Like: return "This is just for ending")
EDIT:
The "bob" funtion is an example for a function that takes 10 seconds, but the plan is to use it on other functions, that can take an undefined amount of time. And that function can't be edited to add simply something to stop it at some time seconds.
A better example could be "pep" as it wouldn't end by itself.
def pep():
import time
while True:
print("Working")
time.sleep(1)
You can use time.time() to get the current time in seconds before you start your loop and then at the end of each for loop, check how long has passed since then and if it's too long then you can return.
def bob(some_argument, some_more):
import time
start = time.time()
for x in range(10):
print("Working")
time.sleep(1)
if time.time() - start > 5:
return "I took too long"
return "I finished and this is my result"
Obviously replace 5 with the time you want to use, but this code gives me this output:
Working
Working
Working
Working
Working
'I took too long'
You may use the break;
For example if the value of the loop counter meets a following condition like this:
if condition:
break;
this will surely end the loop.

Categories

Resources