Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a function that scrapes websites and returns a statement that is depending if it found certain keywords. This function is called checksite. When I run the function on its own it works great but I can't get it to work inside another function together with time.sleep.
This works great
checksite()
This does not work
while True:
checksite()
time.sleep(10)
I want the checksite-function run every 10 second. All help is appreciated!
Your code should work. To check what is wrong, you could use this:
def checksite():
#blahblah
while True:
print('starting')
checksite()
print('site checked')
time.sleep(10)
print('sleep function complete')
Then maybe you will get an idea of what is wrong.
It is important to know what the checktime() execution does.
If you dont see anything happening after 10 seconds and the script still executing more than expected, my first suggestion would be to know how much time the execution takes.
You can run this and get the amount of time:
import time
import datetime
def checktime():
#Doing some execution
print('execution...')
#Use:
while True:
started = datetime.datetime.now()
checktime()
time.sleep(10)
executed = datetime.datetime.now()
print('The script runtime is: {0}'.format(executed - started))
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
I was the other day trying to create on python a little program who would detect if the key x is pressed, if yes the program continue and do it's task. i found the way to do it with the package keyboard :
while True :
if keyboard.is_pressed("x"):
...
But it appears that the while true loop after a long time, start bugging, and that brought to ask you, if it is possible to do a loop or something to detect a key press without causing lags like the window system events when you click on a shortcut then a program appears.
Thank you.
The keyboard documentation specifically says NOT to use the method you are using:
import keyboard
# Don't do this!
#
#while True:
# if keyboard.is_pressed('x'):
# print('x was pressed!')
#
# This will use 100% of your CPU and print the message many times.
# Do this instead
while True:
keyboard.wait('x')
print('x was pressed! Waiting on it again...')
# or this
keyboard.add_hotkey('x', lambda: print('x was pressed!'))
keyboard.wait()
I would recommend reading the documentation for your specific needs.
Note:
If you are looking to bind the specific key to a function, you could do something like this:
import keyboard
def on_x_key_press():
print("'x' key pressed")
keyboard.on_press_key("x", on_x_key_press)
Now your computer runs through that loop as fast as it can. I think you could add a limit on how many times the keyboard press is checked.
import time
while True:
if keyboard.is_pressed("x"):
...
time.sleep(0.001) # the program just sleeps for 0.001 seconds
If the program still lags, try to increment the value of seconds to wait (for example: from 0.001 to 0.005).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 months ago.
Improve this question
im use speechrecognition, and tkinter, i have speech recognition in a inifinte loop, because i want them to recognize my voice all the time together with a GUI of tkinter, i need I need them to run in the same program since I want the gui to change along with the voice recognition but if anyone can give me another solution is welcome
you can use multithreading, you can visit this link to find out how to do that.
https://www.geeksforgeeks.org/multithreading-python-set-1/
Maybe Timers could work?
from threading import Timer
from time import sleep
x0 = 0
x1 = 0
def process1():
global x0
print(x0)
x0 = x0 + 1
Timer(0, process1, []).start()
def process2():
global x1
print(x1)
x1 = x1 - 1
Timer(0, process2, []).start()
Timer(0, process1, []).start()
Timer(0, process2, []).start()
In a similar fashion to javascript's setTimeout.
Eg instead of an infinite loop, you break your loop down into steps, and have it do a timer to do the next step, allowing the other "process" do its thing. This would behave like multithreading on a single thread.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I want to avoid bot detection and my random stuff isn't working. Actually it's not hitting dislike at all. Xpaths are all right. What am I doing wrong here?
def auto_swipe(self):
while True:
sleep_time = random.randrange(1, 3)
time.sleep(sleep_time)
try:
rand1 = random.randrange(0,100)
if rand1 < random.randrange(70,80):
self.like()
else:
self.dislike()
except Exception:
try:
self.close_popup()
except Exception:
self.close_match()
The standard way to use random is as follows. Assuming you'd like something to happen 75% of the time, you'll write the following:
if random.random() < 0.75:
# do something
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am running different Python scripts in Linux and I want to see how much time these scripts, I wonder if there is a command in Bash or in Python it doesn't depend to echo or print to the screen how much time it took to run the command. Thanks in advance.
For example the Python script might be :
import subprocess
command = ['sudo', '-S', 'iwlist', 'wlan0', 'scan']
output = subprocess.Popen(command, stdout=subprocess.PIPE).stdout.read()
data = []
for cell_item in output.split("Cell"):
data_item = []
for line in cell_item.split("\n"):
if any(item in line for item in ["ESSID", "Quality", "Pairwise"]):
data_item.append(line.strip())
if data_item:
data.append(data_item)
print data
What I want is to see on the screen under the last line of some code outputs, I want to see there i.e. ; "This Code Lasted 16.363 seconds"
Just put time before any other command or script e.g.:
time sleep 4
gives
real 0m4.003s
user 0m0.000s
sys 0m0.001s
You can change format of the output as well, see man time.
Personally I use:
from datetime import datetime
t1 = datetime.now()
bashCommand = "df -h > space.txt"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
t2 = datetime.now()
total = t2-t1
print total
So based on the comments, the question appears to be "how can I retroactively see how long my previous commands took?" The answer is simple: you can't.
Python does not automatically time itself when it's running code, and all import time will do is give you access to functions to do the timing yourself. If you ever want to know how long something takes, you have to explicitly say so before the fact. After the code is run, I can't think of anything that will go back and determine how long it took to run. I believe you're going to have to do all of your timing again, sorry to say.
Use bash's special variable SECONDS:
SECONDS=0
script.py
echo $SECONDS
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I'm pretty new to Python and would like to write a (not computer) language trainer for my students. Just something like where a timer runs in the background and the student has to input words quickly to slow down/revert the countdown - otherwise the countdown reaches zero and displays some "game over" message. (Just like when a special agent has to defuse a bomb while the timer races towards zero.)
There are tons of explanations of threading which sounds like the right way to do it, sure, but so far I haven't found anything where a timer is combined with a (time-limited) raw_input. Could any of you pros give me a pointer to the tutorial/discussion I have overlooked?
import threading
import time
import os
def ask():
"""
Simple function where you ask him his name, if he answers
you print message and exit
"""
name = raw_input("Tell me your name, you have 5 seconds: ")
exit_message = "Wohoho you did it..Your name is %s" % name
exit(exit_message)
def exit(msg):
"""
Exit function, prints something and then exits using OS
Please note you cannot use sys.exit when threading..
You need to use os._exit instead
"""
print(msg)
os._exit(1)
def close_if_time_pass(seconds):
"""
Threading function, after N seconds print something and exit program
"""
time.sleep(seconds)
exit("Time passed, I still don't know your name..")
def main():
# define close_if_time_pass as a threading function, 5 as an argument
t = threading.Thread(target=close_if_time_pass,args=(5,))
# start threading
t.start()
# ask him his name
ask()
if __name__ == "__main__":
main()
You don't have to do it via threading, you could in a single thread run through your 'logic' at a specific frequency and each iteration recalculate the countdown via a time-delta method. This is how many video games are produced.
Lets say you run this pseudo-code method at 60hz:
delta = timenow-timelast;
countdown -= delta;
if(input)
processInputHere;
You should be able to convert the pseudo-code to python code to make it work