if (time.clock() > 10:
DO SOMETHING
this only works with 1 iteration of the function then the time.clock surpasses 10seconds.
How do I do:
if (time.clock > time.clock + 10):
how do I save a value for the clock at a particular instance??
I have already tried the get_time() function although this doesn't work on the account that python throws an attribute error
You can save time.clock in a variable
first_instance = time.clock()
if (time.clock > first_instance + 10):
you could rather do
import time
time.sleep(10)
#do something.
You could also use the modulus operator
if(time.clock() % 10 == 0)
#do something
But this will make something happen after every 10th second, and also at the 0th second. But the benefit would be being able to change the behavior to work every 11th second for example which maybe would be preferable or every 12th second. For example every 15th second would be:
if(time.clock() % 15 == 0)
#do something
Related
I'm trying to learn python and while learning I've come across a bit of a problem.
import time
import pyautogui
def SendScript():
time.sleep(2)
with open('script.txt') as f:
lines = f.readlines()
for line in lines:
time.sleep(2)
pyautogui.typewrite(line.strip())
pyautogui.press('enter')
SendScript()
I'm trying to print something to the screen every second time the 'enter' key has been pressed, but I'm an extreme beginner so I really don't know how to do that. Could someone help me accomplish this task?
You could create a new boolean variable to track if the enter key has been pressed before. That way, every time the for loop iterates, the value of pressed switches and only when the value of pressed is True will it print something.
import time
import pyautogui
def SendScript():
pressed = False
time.sleep(2)
with open('script.txt') as f:
lines = f.readlines()
for line in lines:
time.sleep(2)
if pressed:
print("Something")
pressed = not pressed
pyautogui.typewrite(line.strip())
pyautogui.press('enter')
SendScript()
From a more step-back approach, you could do:
events=['event1', 'event2', 'event3', 'event4', 'event5', 'event6', 'event7', 'event8']
counter = 0
for event in events:
counter += 1
if counter % 2 == 0: # ie do stuff when divisible by 2, ie when its even
print('print what you want to be printed every second time')
else:
pass
Of course you are not looping through events like I do in this example. The point is counting the events and only doing stuff when this count is even.
As indicated in another answer already, a simple toggle can be implemented with a bool and then code which toggles it every time something happens:
thing = False
:
if happens(something):
thing = not thing
This is fine for toggling between two states. A more general approach which allows for more states is to use a numeric variable and a modulo operator:
times = 0
maxtimes = 12
:
if happens(something):
times += 1
if times % maxtimes == 1:
print("ding dong")
The modulo could be compared to 0 instead if you want to print on the 12th, 24th etc iterations instead of the first, the 13th, etc, or of course any other offset within the period if that's what you want.
Another useful trick is to flip-flop between zero and some other value.
value = 0
othervalue = 1234
:
if happens(something):
value = othervalue - value
Of course, you can flip-flop between any two values actually; subtract the current value from their sum to get the other one.
Needless to say, just toggling or flip-flopping isn't very useful on its own; you'd probably add some (directly or indirectly) user-visible actions inside the if happens(something): block too.
You could use a generator for this:
def everySecondTime():
while True:
yield "hi"
yield "not hi"
mygen = everySecondTime()
print(next(mygen))
print(next(mygen))
print(next(mygen))
print(next(mygen))
This prints
hi
not hi
hi
not hi
I'm sure it's clear to you how you could adapt this to do some other actions instead.
Whether this approach is better than just using a boolean is highly debatable, but I thought I'd leave it here so you could learn about generators (the yield keyword) if you want to.
I tried to make a timer by making a function, that should keep on running until it hit 0. I thought I could get it to loop, but I think it ended up skipping the first part of else
"(int(time) - int(1))" and just repeating the second numeral it got after - 1.
What i want it to do: Take the whole function and run it through until it reaches 0.
What it does: takes time -1 and keeps printing that until it reaches maximum recursion depth.
import time as tm
def Timer(time):
if time == '0':
print("done")
tm.sleep(3)
else:
print(int(time) - int(1))
Timer(time)
Timer(time)
Assuming time is not a global, you need to pass time as input into your function and modify it accordingly so that you will eventually reach your recursive base case of time == '0'. Currently you are just calling Timer() over and over without changing the time, so you are going to keep recursively calling Timer() until you reach maximum recursion depth as you indicated (printing the changed time is not actually changing the time).
import time as tm
def Timer(time):
if time == '0':
print("done")
else:
print(int(time) - 1)
tm.sleep(1)
time = str(int(time) - 1)
Timer(time)
Timer('4')
Try this
def Timer(time):
for i in range(time,0, -1):
print(time -1)
print("done")
Timer(10)
If you really want a timer, look at importing time and use time.sleep(10)
from time import time
def Timer(time):
for i in range(time,0, -1):
time.sleep(1)
print(time - 1)
print("done")
Timer(10)
I made some small alterations on your code. Though it's very similar, I fixed the missing parameter and removed all the variable type convertions, since it didn't seem necessarry. Here's what I created (of course, you may have to adapt the function calling and probably remove my input):
import time as tm
def Timer(time):
while (time>0):
tm.sleep(1)
time -= 1
print(time)
print("done")
tm.sleep(3)
time=int(input('Choose your time value: '))
Timer(time)
I'm trying to ucreate a timer function that runs in the background of my code and make it so I can use/check the time. What I mean by use/check, I'm trying to make it so I can call upon that timer function and use it as integer.
This is the code I currently have:
def timer():
for endtime in range(0, 15):
print(15 - endtime)
time.sleep(1)
def hall():
timer()
while (timer > 0):
do something
Currently only using print(15 - endtime) for confirmation it is counting down.
But what the code does now is execute the countdown and that's it, it never touches the while loop. And of course the last issue is I can't set a function to an int. So I'm looking for some way where I can check where the timer is at and use it in that while loop.
The way you do it, you'll going to have to use multithread.
Here is another, simpler approach :
On your script beginning, set a time_start variable with the number of seconds since the epoch using time.time()
Then when you need the number of elapsed seconds, use time.time() - time_start :
t_start = time.time()
# do whatever you'd like
t_current = int(time.time()-t_start) # this way you get the number of seconds elapsed since start.
You can put that in a function as well, defining t_start as a global variable.
import time
t_start = time.time()
def timer():
global t_start
print(str(int(time.time()-t_start)))
print('start')
time.sleep(2)
timer()
time.sleep(3)
timer()
import time
def timer(tim):
time.sleep(1)
print tim
def hall():
tim = 15
while (tim > 0):
print 'do something'
timer(tim)
tim-=1
Not the cleanest solution, but it will do what you need.
The problem with your code is that when you run hall(), Python first executes the whole of timer() (i.e. the whole for loop), and then moves on with the rest of the code (it can only do one thing at a time). Thus, by the time it reaches the while loop in hall(), timer is already 0.
So, you're going to have to do something about that timer so that it counts down once, and then it moves on to the do something part.
Something that you can do is this:
def hall():
for a in range(0, 15):
print(15 - a)
# do something
time.sleep(1)
This should work just fine (if you're only executing hall 15 times), and condenses your code to just one function.
I want to make my function trigger at 0 second,30second every minute.
Rather than use time.sleep(30) because the script will run for months and have some blocking system call,
I want to make it happens on specific time like 12:00:00, 12:00:30, 12:01:00
How could I do it on Python 2.7
Not sure how your function works but if there is any sort of a loop you could use an if statement.
t = time.time()
while/for loop:
...
if time.time() > t + 30:
yourFunction()
t = time.time()
...
EDIT:
My fault, misread that. Similar method but you can use date time, probably better off looking into chrontab though. This method is a little hacky and if your script is small and can cycle every second this will work, otherwise go chrontab.
import datetime
t = datetime.datetime
run = True
while/for loop:
...
if t.now().second % 30 == 0 and run == True:
yourFunction()
run = False
if t.now().second % 30 == 1:
run = True
...
Here's my code, it's just supposed to basically change end to start + 25 minutes.
I'm just wondering if there is a way to update datetime.datetime.now() to be the current time.
As it stands, it just stays at whatever it was when I first used the module.
So the if statement will never be true.
import datetime
start = datetime.datetime.now()
end = start + datetime.timedelta(minutes = 25)
if start == end:
end = end + datetime.timedelta(minutes = 25)
As CharlesB has suggested, the start variable is not updated. You need to take the now value at the time you want to perform the test.
Rewrite the line:
if start == end:
To
if datetime.datetime.now() > end:
EDIT
After Tommo's comment, I think another solution may be easier.
import time
while True:
putMessageToScreen()
time.sleep(25*60)
If you want a value to change on subsequent references, you want to use a function call, not a stored variable.
In principle, you could make the above code do what you want by subclassing datetime.datetime and defining the __add__ method to recompute datetime.datetime.now(), but it wouldn't be a good idea.