im trying to write a very basic sleep interval script and a starter script
but for some reason that I can't understand I get an error message
CODE:
def intervals():
while True:
try:
interval = input('[?] Intervals in seconds [default = 0s]:\t') or 0
interval = int(interval)
print(f'[+] Sleep for: {interval} seconds after each message Sent')
return interval
except:
print(f'[!] Error: {interval} Not a number')
def intervals_start(interval):
sleep(interval)
intervals()
intervals_start(interval)
ERROR:
[?] Intervals in seconds [default = 0s]: 5
[+] Sleep for: 5 seconds after each message Sent
Traceback (most recent call last):
File "***********/testing.py", line 49, in <module>
intervals_start(interval)
NameError: name 'interval' is not defined
Process finished with exit code 1
You are passing a variable interval into a function intervals_start(), but nowhere in the code did you assign interval a value.
You need to capture the result of intervals()
interval = intervals()
then you can safely pass the user selected interval into intervals_start()
Related
I'm trying to schedule something to run periodically, using the code below:
import sched
import time
from datetime import datetime, timedelta
def foo(s, t_end):
now = datetime.now()
print(now)
# Schedule the next run of this function, but only if it'll be before 't_end'
next_run = now + timedelta(seconds=1)
if next_run <= t_end:
s.enter(1, 1, foo, (s, t_end,))
# s.enterabs(next_run, 1, foo, (s, t_end,)) # <-- why doesn't this work?
if __name__ == '__main__':
s = sched.scheduler(time.time, time.sleep)
t_end = datetime.now() + timedelta(seconds=5)
foo(s, t_end)
s.run()
This runs exactly like it should... the script calls foo exactly 5 times and then exits (with 1 second delay between the calls).
But if I change the s.enter(...) to s.enterabs(...) and pass in the calculated time when foo should be called again, it throws the following error:
Traceback (most recent call last):
File "/tmp/test.py", line 18, in <module>
s.run()
File "/usr/lib/python3.9/sched.py", line 141, in run
if time > now:
TypeError: '>' not supported between instances of 'datetime.datetime' and 'float'
What am I doing wrong?
OK I figured this out. In the call to s.enterabs(...), I need to pass next_run.timestamp() as the first argument (not just next_run).
I tried to make it as easy as possible to understand, I have no backgound in IT, I am doing this auto login program to join my own classes. Can anyone tell me why its not working?
The error is this :
"Traceback (most recent call last):
File "/home/omiceyo/PycharmProjects/datetimepractice/main.py", line 79, in <module>
Wednesday()
File "/home/omiceyo/PycharmProjects/datetimepractice/main.py", line 56, in Wednesday
schedule.every().Wednesday.at(Class).do(join_meeting(666666666))
AttributeError: 'Job' object has no attribute 'Wednesday' "
Here is my code:
import datetime
import schedule
import subprocess
import pyautogui
import time
#Define join meeting
def join_meeting(meetingid):
# open Tencent Meeting windows 10
subprocess.call(["C:\Program Files (x86)\Tencent\WeMeet\wemeetapp.exe"])
# 5 secs wait for lag
time.sleep(5)
# Click join button
join_button = pyautogui.locateCenterOnScreen('Tencent_meeting_join_button.png')
pyautogui.moveTo(join_button)
pyautogui.click()
# Putting in the Meeting ID
Id_button = pyautogui.locateCenterOnScreen('Tencent_meeting_id.png')
pyautogui.moveTo(Id_button)
pyautogui.click()
pyautogui.write(meetingid)
# Disable mic
mic_button = pyautogui.locateCenterOnScreen('mic_button.png')
pyautogui.moveTo(mic_button)
pyautogui.click()
# time.sleep(4)
# Joining the meeting
Meeting_button = pyautogui.locateCenterOnScreen('Join_meeting.png')
pyautogui.moveTo(Meeting_button)
pyautogui.click()
time.sleep(4)
pyautogui.press('enter')
#Class times
Class = "10:00"
Class2= "14:00"
Class3= "16:00"
Class4= "19:00"
Test= "18:25"
#Define weekdays
def Monday():
schedule.every().Monday.at(Class2).do(join_meeting(6666666))
def Tuesday():
schedule.every().Tuesday.at(Class3).do(join_meeting(6666666))
def Wednesday():
schedule.every().Wednesday.at(Class).do(join_meeting(666666666))
schedule.every().Wednesday.at(Class2).do(join_meeting(66666666))
schedule.every().Wednesday.at(Test).do(join_meeting(6666666666))
def Thursday():
schedule.every().Thursday.at(Class4).do(join_meeting(666666666))
def Friday():
schedule.every().Friday.at(Class4).do(join_meeting(66666666))
def Saturday():
print("Its saturday")
Date = datetime.datetime.now()
Today = (Date.strftime("%a"))
if Today=="Mon":
Monday()
elif Today=="Tue":
Tuesday()
elif Today=="Wed":
Wednesday()
elif Today=="Thu":
Thursday()
elif Today=="Fri":
Friday()
elif Today=="Sat":
Saturday()
else:
print("Today is sunday")
while True:
schedule.run_pending()
time.sleep(60)
Check the capitalization for the days of the week per their documentation.
wednesday will get called now but will run into a type error associated with join_meeting(meetingID):
TypeError: the first argument must be callable
A quick resolution to the TypeError is to not pass the meetingid through the scheduler and define it else where, example:
schedule.every().wednesday.at(Class2).do(join_meeting)
Also, the while loop is indented too far and won't run.
I am trying to run a function every 2 minutes, and I use apscheduler for this. However, when I run this I get the following error:
Traceback (most recent call last):
File "main_forecast.py", line 7, in <module>
scheduler.add_job(get_warnings(), 'interval', seconds = 120)
File "/home/anastasispap/.local/lib/python3.6/site-packages/apscheduler/schedulers/base.py", line 434, in add_job
job = Job(self, **job_kwargs)
File "/home/anastasispap/.local/lib/python3.6/site-packages/apscheduler/job.py", line 49, in __init__
self._modify(id=id or uuid4().hex, **kwargs)
File "/home/anastasispap/.local/lib/python3.6/site-packages/apscheduler/job.py", line 170, in _modify
raise TypeError('func must be a callable or a textual reference to one')
TypeError: func must be a callable or a textual reference to one
And here's the code:
from apscheduler.schedulers.background import BackgroundScheduler
from enemies_info import get_warnings
import time
scheduler = BackgroundScheduler()
scheduler.add_job(get_warnings(), 'interval', seconds = 120)
scheduler.start()
while True:
time.sleep(120)
The function I want to run every 2 minutes is get_warnings.
def get_warnings():
print('get_warning has been run')
names = []
types = []
number_of_threats = 0
forecast_weather()
for i in range(0, number_of_enemies):
enemies = info["enemies"][i]
name = enemies["name"]
type = enemies["type"]
temperature = enemies["temperature"]
temperature = temperature.split("-")
min_temp = temperature[0]
max_temp = temperature[1]
for i in range(len(temperatures)):
if avg_temps[i] <= str(max_temp):
names.append(name)
types.append(type)
number_of_threats += 1
break
os.chdir('..')
write_data(number_of_threats, names, types)
move_to_github()
You are calling the function get_warnings, instead of providing it as a callable. Try:
scheduler.add_job(get_warnings, 'interval', seconds = 120)
Using time.time() as a means to schedule a task easily, but for some reason, I keep getting an error which doesn't make a lot of sense to me. I printed timenow and it reads correctly.
Code:
timenow = time.time()
def my_BidAsk(msg):
global timenow
tnow = time.time()
if (tnow - timenow) >= 60:
resample()
timenow = time.time()
Here is the error I get, but it doesn't make sense because whether I predefine it or not, globally or locally, the error is still the same. Any idea why?
06-Dec-16 01:09:18 ERROR Exception in message dispatch. Handler 'my_BidAsk' for 'tickPrice'
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/ib/opt/dispatcher.py", line 44, in __call__
results.append(listener(message))
File "/Users/usr/Desktop/Hobbies/Coding/connect-contract-order IB.py", line 57, in my_BidAsk
tnow = time.time()
UnboundLocalError: local variable 'time' referenced before assignment
I had a similar issue which I was able to resolve. In my case, I had a local variable called "time" initialized later in the same function. Using the name of a library as a local variable name causes the exception to be raised when the script runs "t_start = time.time()".
To solve this, I renamed my local variable from "time" to something unoffending (in my case, "time_s"). Ignore any bad pandas practices...
t_start = time.time()
for index, row in profile.iterrows():
time = row['time_s']
current = row['Current']
voltage = row['Voltage_V']
soc = row['SOC']
changed to:
t_start = time.time()
for index, row in profile.iterrows():
time_s = row['time_s']
current = row['Current']
voltage = row['Voltage_V']
soc = row['SOC']
problem
I have written a small program to implement a stopwatch. This stopwatch will begin when s is pressed and stop running when l is pressed. For this I have used the following code:
f = self.frame
w = self.window
info = Label(f,text="\nPress \'s\' to start running and \'l\' to stop running\n")
info.pack()
w.bind('<KeyPress-s>',self.startrunning)
w.bind('<KeyPress-l>',self.stoprunning)
The stoprunning and start running functions are as so:
def startrunning(self):
r = Frame(self.window)
r.pack()
self.start = time.time()
start = Label(r,text="\nStarted running")
start.pack()
def stoprunning(self):
r = Frame(self.window)
r.pack()
self.stop = time.time()
self.timeConsumed = self.stop - self.start
Label(r,text='\nstopped running').pack()
end = Label(r,text="\nTime consumed is: %0.2f seconds" %self.timeConsumed)
end.pack(side = "bottom")
Error
On pressing the s key I get the following error:
>>>
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python25\lib\lib-tk\Tkinter.py", line 1414, in __call__
return self.func(*args)
TypeError: startrunning() takes exactly 1 argument (2 given)
Specs
Python 2.7
I am new to tkinter programming and am unable to understand what or why this error is being shown. Please tell me if I am using the code correctly. Also please help me resolve this problem.
use
def startrunning(self,ev):
def stoprunning(self,ev):
bind send event to a subroutine (http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm).
alternate, you can describe bind as
w.bind('<KeyPress-s>',lambda ev:self.startrunning())
w.bind('<KeyPress-l>',lambda ev:self.stoprunning())