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.
Related
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/
I am an PHP developer, i've never used python before, now i'm implementing am SMS system on our project, it's already working, but as i dont like python i've just made a little script with some information i collected over the web and i call this script using an php, the python script is
#!/usr/bin/python
import urllib, sys
import serial
import time
for arg in sys.argv:
if arg == "-t":
recipient = sys.argv[2] # numero
elif arg == "-m":
message = sys.argv[4] # mensagem
phone = serial.Serial("/dev/serial0", 9600, timeout=5)
try:
time.sleep(0.2)
phone.write(b'ATZ\r')
time.sleep(0.12)
phone.write(b'AT+CMGF=1\r')
time.sleep(0.12)
phone.write(b'AT+CMGS="' + recipient.encode() + b'"\r')
time.sleep(0.12)
phone.write(message.encode() + b"\r")
time.sleep(0.12)
phone.write(bytes([26]))
time.sleep(0.12)
finally:
phone.close()
print('OK')
And i call it passing the vars on php like:
$recipient = "+5511anyphonenumber";
$message = "'Estou fazendo um teste'";
$command = "python3 teste2.py -t $recipient -m $message";
exec($command);
The only problem is that i need the script to run only once per 3 seconds, so if it is called once and is called again 2 seconds after, i need the second call to be queued until 3 seconds has been passed from the last call, is there any easy way to do this? Please take in count that i'm not familiar with python.
You can use a list (something like an array) to store any calls that come during the 3 seconds. As the calls come, append them to the list (use the append() method - <list>.append(<object>)
).
After, 3 seconds are over, execute the first element of the list: <list>[0] and remove it from the list:
<item> = <list>.pop(0)
(You can execute the <item>)
If you want to accept calls simultaneously during the three seconds while other processes are going, then, use the threading module to accept the calls while running the original process and to store these calls to execute after 3 seconds.
I take it the 3 seconds is just an arbitrary duration it takes for the program has finished doing its thing, not a hard limit?
You'll probably want to use a lock file of some sort to avoid concurrent executions. Take a look at fasteners (as suggested in the now-deprecated lockfile); it's designed to do things right (there are certain race-condition/atomicity corner cases you need to take care of if you decide to roll your own.)
I am trying to make a simple program in komodo edit using python that when it runs will print out 10 seconds worth of time in the command output.
The code is as follows:
import time
seconds = 0
while seconds != 10:
time.sleep(1)
seconds += 1
print(">", seconds)
When I run this in komodo edit, it doesn't print out the numbers as wanted.
I want the number 1 to be printed after one second of time, the number 2 to be printed after two seconds of time, and etc.
Instead, it prints out all the numbers (1-10) after 10 seconds of time.
I have run this exact same program in the python IDLE and it works as it should, printing one number per second.
What am I doing wrong or what do I not understand/know about?
The program is likely running in an environment where it does not believe its output is connected to a terminal, so stdout defaults to block buffering, not line buffering. Since you're outputting very little data, the buffer never fills, and is only flushed just before the program exits.
The simplest fix is to add the flush=True argument to your print call, so the buffer is explicitly flushed after each print:
print(">", seconds, flush=True)
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
I have a Python program that navigates me to a website with a function that I have defined as nav(a, b), and on this site I will be downloading some pyfits data for use on another script. This site has a different pyfits file for every set of (a,b) in a catalog I have.
I was wondering if I could iterate through this catalog using a for loop, and each time the nav(a, b) function is used, tell python to pause while I download the file, then resume again when I tell it to. I've done something like this in IDL before, but don’t know how with Python.
Otherwise I guess I'm stuck running the program 200 times, replacing the (a, b) values each time, which will take for ever.
If you want to wait for a manual signal to continue, wait for the user to press Enter:
Python 2:
raw_input("Press Enter to continue...")
Python 3:
input("Press Enter to continue...")
If you can download the file in the python code, do that instead of doing the manual task for each of the files.
You can use time.sleep() to pause the execution for t seconds:
import time
time.sleep(1.3) # Seconds
Demo:
import time
print "Start Time: %s" % time.ctime()
time.sleep(5)
print "End Time: %s" % time.ctime()
Output
Start Time: Tue Feb 17 10:19:18 2009
End Time: Tue Feb 17 10:19:23 2009
Use a while loop, waiting for your download to finish:
for ... :
nav(a,b)
while downloading_not_finished:
time.sleep(X)
So, every X period of time a condition is tested, and is tested again until the downloading part is finished.
Okay, here are two ways to pause in Python.
You can use the input function.
# Python 2
raw_input("Downloading....")
# Python 3
input("Downloading....")
This will pause the program until the user presses Enter, etc.
You can use the time.sleep() function.
import time
time.sleep(number of seconds)
This will pause the Python script for however many seconds you want.
For Python shell in design:
import sys
from time import sleep
try:
shell = sys.stdout.shell
except:
print('Run It In Shell')
dots = '........';
shell.write('Downloading')
sleep(0.5)
for dot in dots:
shell.write(dot)
sleep(0.1)
shell.write('\n')
sleep(0.4)
shell.write('Saving Files')
sleep(0.5)
for doot in dots:
shell.write(dot)
sleep(0.1)
shell.write('\n')
sleep(0.4)
For Python in a console:
from time import sleep
print('Downloading')
sleep(1)
print('Saving Files')
sleep(1)
Use the input function. It will pause the program until the prompt has been closed/filled in.
The best solution is to put another while loop inside the existing while loop:
while True:
#do something
asleep = True
while (asleep):
if cv2.waitKey(1) == 32: #Wait for space key
asleep = False