As you see in the below code, it is possible to open a file in a directory and read it. now i want live_token read the file every 30 minutes and print it. Can anyone help me in this regard?
I found below code as scheduling to do a job but i don't know how to do needful modifications.
schedule.every(30).minutes.do()
Sorry if this question is so basic, I am so new with Python.
def read_key():
live_key_file_loc = r'C:\key.txt'
live_key_file = open(live_key_file_loc , 'r')
global key_token
time.sleep(6)
live_token=live_key_file.read()
print(live_token)
import time
sleep_time = 30 * 60 # Converting 30 minutes to seconds
def read_key():
live_key_file_loc = r'C:\key.txt'
live_key_file = open(live_key_file_loc, 'r')
global key_token
time.sleep(6)
live_token = live_key_file.read()
print(live_token)
while(True): # This loop runs forever! Feel free to add some conditions if you want!
# If you want to read first then wait for 30 minutes then use this-
read_key()
time.sleep(sleep_time)
# If you want to wait first then read use this-
time.sleep(sleep_time)
read_key()
#jonrsharpe is right. Refer to schedule usage. You should have a script which should keep running always to fetch the token every 30 minutes from the file. I have put below a script which should work for you. If you dont want to run this file in python always, look for implementing a scheduled job.
import schedule
import time
def read_key():
with open('C:\\key.txt' , 'r') as live_key_file_loc
live_token = live_key_file_loc.read()
print(live_token)
schedule.every(30).minutes.do(read_key)
while True:
schedule.run_pending()
time.sleep(1)
There are a few steps in this process.
Search for “Task Scheduler” and open Windows Task Scheduler GUI.
Go to Actions > Create Task…
Name your action.
Under the Actions tab, click New
Find your Python Path by entering where python in the command line. Copy the result and put it in the Program/Script input.
In the "Add arguments (optional)" box, put the name of your script. Ex. - in "C:\user\your_python_project_path\yourFile.py", put "yourFile.py".
In the "Start in (optional)" box, put the path to your script. Ex. - in "C:\user\your_python_project_path\yourFile.py", put "C:\user\your_python_project_path".
Click “OK”.
Go to “Triggers” > New and choose the repetition that you want.
For more details check this site -
https://www.jcchouinard.com/python-automation-using-task-scheduler/
Related
Problem
I want to write a program in Python, where a script executes when it detects that it has been brought out of sleep mode.
E.g I am using a laptop. When I open the laptop, the script should run. Is there a way to detect this and then run a script? Is there a module for listening for such events?
Goal
The ultimate goal is a sort of security system, where an alert is sent to a users phone, if their computer is used. I have an idea for the alert sending part, I just can't figure out how to trigger the program in the first place.
The basic format should look something like this:
if computer_active == True:
alert.send("Computer accessed")
Obviously it would look more complicated than that, but that's the general idea.
I'm running Python3.10.0 on MacOSX v10.15.7
Any help is greatly appreciated!
A maybe-better-than-nothing-solution. It's hacky, it needs to run always, it's not event driven; but: it's short, it's configurable and it's portable :-)
'''
Idea: write every some seconds to a file and check regularly.
It is assumed that if the time delta is too big,
the computer just woke from sleep.
'''
import time
TSFILE="/tmp/lastts"
CHECK_INTERVAL=15
CHECK_DELTA = 7
def wake_up_from_sleep():
print("Do something")
def main():
while True:
curtime = time.time()
with open(TSFILE, "w") as fd:
fd.write("%d" % curtime)
time.sleep(CHECK_INTERVAL)
with open(TSFILE, "r") as fd:
old_ts = float(fd.read())
curtime = time.time()
if old_ts + CHECK_DELTA < curtime:
wake_up_from_sleep()
if __name__ == '__main__':
main()
I write a bot that should automatically register me for an exam.
The bot should be faster than a human especially the to last lines(will add them below)
I will open the python script a few minutes before the time it need to be executed.
I am looking for a solution to the following problem:
My code (its in production I will change the username and password variable to not be plaintext).
I will also wrap it in functions.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from datetime import datetime
import time
path = "my_path"
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=my_user-data-dir")
driver=webdriver.Chrome(path, chrome_options=options)
time_now = datetime.now()
driver.get("linkt_to_website")
login = driver.find_element_by_class_name("Login")
login.click()
user = driver.find_element_by_id("username")
user.send_keys("my_username")
pwd = driver.find_element_by_id("password")
pwd.send_keys("my_password")
lgnbtn = driver.find_element_by_id("loginbutton")
lgnbtn.click()
driver.get("website linkt to the page with the button to register for my exam")
time.sleep(1)
toggle = driver.execute_script("js function to trigger dropdown menue")
# until here it does not make a difference how much time the bot need
until here everything works fine
the goal is that the bot logs in and wait until a predefined time(hour, minutes, seconds, milliseconds)
but now I have a question:
# the two lines below are the most important
anmed= driver.find_element_by_xpath("register button xpath ").click()
last_btn= driver.find_element_by_xpath("are you sure register button ").click()
The two button I want to trigger in the two lines above will appear at a given time so I need to make a function to trigger the two lines when its for example exactly 10:00:00 in the morning.
I hope this question makes sense.
The main goal is to start the script a few minutes before "10:00:00"AM it logs in and wait until 10AM and as accurately as possible execute the two last lines to actually register for my exam.
Thank you in advance:)
If you want to pause your code until a particular time, then you essentially want your code to sleep for N seconds where N has been calculated to land at the time you want.
import time
#Time right now in seconds from epoch.
c = time.time()
#Time at 6:10 PM today from epoch.
n = time.mktime(time.strptime('2021:02:09-18:10:00','%Y:%m:%d-%H:%M:%S'))
#Pause code for seconds until it reaches 6:10 PM today.
sleep(n-c)
#Run code after pausing.
I am EST time, so things might be different for you.
Are you sure you don't need to reload the page when for the button to become active? If not, this is a quick and dirty way to use time and datetime to check if the moment is right, and if not, wait (1 second) and try again later. You could check every 0.1 seconds if you think that would be more successful.
You might also want to use a "try" block incase the sync between your computer time and server time don't agree and so you look for a button that does not exist yet and trigger an error thus disrupting your code.
import datetime
import time
trigger_time = datetime.datetime(2021, 2, 9, 22, 0, 0) # Tonight at 10PM
while True:
now = datetime.datetime.now()
if now >= trigger_time:
try:
# RUN CODE
except WHATEVEREXCEPTION_SELENEIUM_THROWS_FOR_MISSING_ELEMENTS:
pass
if code_success:
break
else:
time.sleep(1) # Wait for 1 second
Im having an issue with cronjob to execute a function from a python module Pyautogui called from a python script.
Im currently running this on mac OS and running python through anaconda environment. After reading many StackOverflow & StackExchange posts, I was able to find this one (here) that was super helpful in getting my PATHs and env variables set. Was able to successfully get the python script to run with the job specified in the crontab.
However, just one line of the script (dependent on the Pyautogui module) is not executing. As most of the posts mention, this script runs with no issues when manually ran from terminal but does not result the same through cron.
Here is my crontab to run at 730am Mon-Fri;
SHELL=/bin/bash
HOME=/Users/harrisonw
PYTHONPATH=/Users/harrisonw/anaconda3/lib/python3.7/site-packages
30 7 * * 1-5 cd /Users/harrisonw/Documents/cron_jobs && /Users/harrisonw/anaconda3/bin/python3.7 online_status_pyautoguyi.py >> ~/Documents/cron_jobs/online_status_cron_output.txt
Here is my script w/ the shebang at the top line ; super simple logic to open a url then refresh that webpage every five minutes for 2 hours on a loop.
#!/Users/harrisonw/anaconda3/bin/python3.7
import os
import time
import pyautogui as py
refresh_counter= 0 #counter for whileloop to break after certain number
url= "https://www.facebook.com" #url to access and refresh
os.system("open " + url) #opens url using os library
time.sleep(10) #wait 10 secs for webpage to load
while True: #loop refresh command for 2 hours
time.sleep(300) #wait 5 mins
py.hotkey('command', 'r') #calls hotkey function "Command+R" to refresh page
print("Refreshed")
refresh_counter += 1 #count +1 for each refresh
if refresh_counter == 24: #condition to reach 24 refreshes in 5 min intervals= 2hrs
break
else: #continue loop if 24 is not reached.
continue
print(refreshed_counter)
print("\nComplete")
The line py.hotkey('command', 'r') is the issue im seeking help for.
Here is the output in the file online_status_cron_output.txt as stated in the crobtab above which confirms the script was run.
Refreshed
Refreshed
2
Complete
Im suspecting that Im missing an additional PATH to the Pyautogui module or an env variable in the crontab but not sure how to proceed from here.
Might be a silly question but is Pyautogui compatible with cronjobs?
Any insight and advise around this is appreciated. Thanks!
Suppose I am using VLC Player and I want to calculate the time it takes to boot using python , is there any way?
I have tried winium automation , but elements load too slowly. I want to get boot up time of my application and it boots in 4-5 seconds , whereas winium usually takes more than that to find the location of element.
If anyone can suggest any better way via backend automation, please comment.
If i understood you right, you need to find time from moment you executed the app to the moment the window appears. You can do that with pygetwindow library. Here's the code:
import pygetwindow as pw
import time
# here's code that executing the program, but i just put comment
start = time.time()
while 1: # waiting until window appears
# getWindowsWithTitle method returns empty list if it didn't found any windows with this name
if pw.getWindowsWithTitle('VLC'): #if it founds the window, loop will break
break
stop = time.time()
result = stop - start # result is time in seconds (type float)
EDIT
You also can detect start of application by checking if amount of windows changed.
import pygetwindow as pw
import time
starting_amount = len(pw.getAllWindows()) # amount of windows
# here's code that executing the program, but i just put comment
start = time.time()
while 1: # waiting until window appears
if len(pw.getAllWindows()) > starting_amount: #if amount of windows is bigger than it was before we executed the program
break
stop = time.time()
result = stop - start # result is time in seconds (type float)
This should work with LD Player
This is what I have
file=open(test, 'w')
file.write(GetWindowText(GetForegroundWindow()))
And what I want is to make it write the current window to the txt file every 5 seconds.
For that you need to loop it. The following code should help you.
Updated
Also make the file name to be a string or it will give an AttributeError
import time
filename = "test"
file = open(filename, 'wa') # w+ is to append new lines to the file
while True:
file.write(GetWindowText(GetForegroundWindow()))
time.sleep(5)
You could use time.sleep() if you want to pause for a certain number of seconds.
import time
print("something")
time.sleep(5) # pauses for 5 seconds
print("something")
If you place this in a loop it would print approximately* every 5 seconds. (Not exactly, since your program still needs to execute the other lines in your loop in the meantime. But maybe this is good enough for your purposes.)
If you need it exactly every 5 seconds you can use library schedule. Install with pip install schedule. See https://stackoverflow.com/a/41647114/9216538 for an example.