Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Somehow this is frying my brain, i dont know how to get the function to start again after they are done. The goal is to run them at the same time and when theyre finished they should start again:
if __name__ == '__main__':
current_task += 1
Thread(target = main).start()
current_task += 1
Thread(target = main).start()
pass
You could use a while loop within main:
import threading
import time
def main():
while 1:
print("starting")
time.sleep(2)
print("done")
if __name__ == '__main__':
threading.Thread(target=main).start()
Out:
starting
done
starting
done
starting
...
You could start a new thread at the end of your main-method:
def main():
# .. do some stuff ..
Thread(target=main).start()
if __name__ == '__main__':
current_task += 1
Thread(target = main).start()
current_task += 1
Thread(target = main).start()
pass
This way, both threads spawn a new thread with a new execution once they are done.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 days ago.
Improve this question
I wrote async PyQt code that automatically downloads some files from web with few seconds duration like below:
pop async method
def pop(q):
global globalCnt
global globalLabel
while True:
url = q.get()
if url:
webbrowser.get("firefox").open(url)
globalCnt -= 1
globalLabel.setText = str(globalCnt)
time.sleep(3)
PyQT main window class
(Please assume class MyApp(QWidget) exists)
def MyApp(QWidget):
def initUI(self):
global globalLabel
self.setWindowTitle('Hello PyQT')
self.labelLayout = QHBoxLayout()
self.labelLayout.addStretch(1)
self.labelLayout.addWidget( QLabel("### Count of : ") )
self.labelLayout.addWidget( globalLabel )
self.vlayout.addLayout( self.labelLayout )
self.setLayout(self.vlayout)
self.center()
self.show()
def onEnter(self):
global globalLabel
for i in links:
urlStr = "https://foo.bar" + linkstr[front : end-7]
global globalCnt
globalCnt += 1
globalLabel.setText = str(globalCnt)
que.put( urlStr )
self.urlArray.append( urlStr )
Global section
if __name__ == '__main__':
app = QApplication(sys.argv)
globalCnt = 0
globalLabel = QLabel("000")
ex = MyApp()
que = Queue()
thread1 = threading.Thread( target=pop, args=(que, ) )
thread1.daemon = True
thread1.start()
sys.exit(app.exec_())
I defined global label : gloablLabel and I changed globalLabel different each spot
As I think, gloablLabel increases in onEnter event and decreases in pop method,
but it remains the default value 000.
How can I fix it?
I'd like to run multiple python scripts in parallel and start them from a master script. I did find solutions for this in previously asked questions, however, none of these worked if the scripts running in parallel contained loops.
Let's for example define two scripts.
Script 1:
array_1 = []
x = 0
while True:
array_1.append(x)
x = x + 1
Script 2:
array_2 = []
x = 0
while True:
array_2.append(x)
x = x + 1
Now I want to run both processes simultaneously. Previous solutions suggested the following code for a master script:
import script_1, script_2
exec(open(script_1))
exec(open(script_2))
While this is a solution for starting scripts from within another script, however, this will not run the two scripts in parallel.
What should such a master script actually look like ?
Thanks for your suggestions!
Edit
I tried the following threading approach:
def function_1():
print('function 1 started...')
while True:
print('1')
sleep(1)
def function_2():
print('function 2 started...')
while True:
print('2')
sleep(1)
thread_1 = Thread(target=function_1())
thread_2 = Thread(target=function_2())
thread_1.start()
thread_2.start()
thread_1.join()
thread_2.join()
print("thread finished")
It doesn't work, only the first function gets started so I get the following output:
function 1 started...
1
1
1
1
1
1
When you want to spawn a new thread, you need to pass the address of the function you want the thread to execute, and not to call it. What you are doing here is essentially spawning a new thread that immediately calls function_1() which of course runs forever.
Also, you won't be able to reach this line of code:
print("thread finished")
As the threads are executing a while loop - forever, so it is redundent..
from time import sleep
from threading import Thread
def function_1():
print('function 1 started...')
while True:
print('1')
sleep(1)
def function_2():
print('function 2 started...')
while True:
print('2')
sleep(1)
thread_1 = Thread(target=function_1)
thread_2 = Thread(target=function_2)
thread_1.start()
thread_2.start()
thread_1.join()
thread_2.join()
# print("thread finished") - redundant
This question already has answers here:
How to share a variable between 2 threads
(1 answer)
What is the use of join() in threading?
(12 answers)
Closed 1 year ago.
I have a while True loop that needs to be run in the background to update a variable and a function that needs to return that same variable.
I tried this as a test:
import threading
downspeed = 0
def updating():
while True:
downspeed = downspeed+1
def main():
while True:
print(downspeed)
u = threading.Thread(name='background', target=updating)
m = threading.Thread(name='foreground', target=main)
u.start()
m.start()
But it only returns 0
Your code is not really a sufficient test. The test ought to include:
Allowing some time for the threads to run to see what they do.
Make the threads sleep, at least for a little time, to allow task switches to occur.
See this code:
import threading
import time
can_run = True
downspeed = 0
def updating():
global downspeed
while can_run:
downspeed = downspeed+1
time.sleep(0.1) # Allow taskswitches
def main():
while can_run:
print(downspeed)
time.sleep(1) # Allow taskswitches
u = threading.Thread(name='background', target=updating)
m = threading.Thread(name='foreground', target=main)
u.start()
m.start()
time.sleep(10) # Allow time for the threads to do what they want
can_run = False
print('Done')
u.join()
m.join()
There are no problems sharing variables in python because of the GIL. Although this only makes changes atomic.
I am working on python 3 and my class is as below.
class MyClass():
def values(self):
***values***
i =0
def check_values(self):
for i in ValueList[i:i+1]:
self.server_connect()
new_value = self.update.values(i)
def run(self):
self.check_values()
if __name__ == "__main__"
format1 = "%(asctime)s: %(message)s"
logging.basicConfig(format=format1, level=logging.INFO,
datefmt="%H:%M:%S")
for i in range(4):
thread = threading.Thread(target=MyClass().run())
threads.append(thread)
i += 1
print("the %s thread is running", thread)
thread.start()
There are no threads getting created but code works.
I am not able to catch what I am doing wrong here.
EDIT
First, I would like to thank you for response and time given for the answer.
I have to update code and inherit other class as per new update from team as below.
class MyClass(MainServer):
Now, the server has it's own run function as below.
class MainServer(object):
***constructor***
***other functions ***
def run(self):
self.add_arguments()
self.parse_arguments()
self.check_values()
Now, without run(), my code is not properly running.
while including run() as below.
*** main ***
update_perform = MyClass()
for i range(4):
thread = threading.Thread(target=Myclass().run()) <-- code starts from here
threads.append(thread)
i += 1
print("the %s thread is running", thread)
thread.start() <-- not reaching till here
As per my knowledge I will require thread.start() to start threading. So I have tried below option
class MyClass(MainServer):
***code as above***
def check_values(self):
self.server_authenticate()
update_value = self.update.values()
def run(self):
self.server_connect()
i = 0
threads = list()
for i in ValueList[i:i+1]:
print("Updating the value = ", i)
thread = threading.Thread(target=check_values(), args=[i])
thread.start()
i += 1
print("Currently running thread", thread)
threads.append(thread)
for thread in threads:
thread.join()
Here thread is executing from start and in print I can see as below
for threading :-
Currently running threads = <Thread(Thread-8, stopped 14852)>
But for the value I can see only one is in process as below
for value :-
Updating the value = 10 <- first value
So, now threads may be getting created but the values are not getting executed in parallel.
Which I am not able to figure out.
modify the run function like this
def run(self):
self.check_values()
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 5 years ago.
Improve this question
I am trying to create a program which takes a target time (like 16:00 today) and counts down to it, printing each second like this:
...
5
4
3
2
1
Time reached
How can I do this?
You can do this using python threading module also, something like this :
from datetime import datetime
import threading
selected_date = datetime(2017,3,25,1,30)
def countdown() :
t = threading.Timer(1.0, countdown).start()
diff = (selected_date - datetime.now())
print diff.seconds
if diff.total_seconds() <= 1 : # To run it once a day
t.cancel()
countdown()
For printing "Click Now" when countdown gets over, you can do something like this :
from datetime import datetime
import threading
selected_date = datetime(2017,3,25,4,4)
def countdown() :
t = threading.Timer(1.0, countdown)
t.start()
diff = (selected_date - datetime.now())
if diff.total_seconds() <= 1 : # To run it once a day
t.cancel()
print "Click Now"
else :
print diff.seconds
countdown()
This will result in something like this every second :
2396
2395
2394
2393
...