Reputation: 319
I want to trigger upfunction
and stop when it writes 3 in the filename. Basically I want to stop a thread once the condition is met as shown below.
def getstatus():
fh = open(filename,'r')
return fh.read()
def upfunction(arg):
for i in range(arg):
print ("backup running")
print(getstatus())
target = open(filename, 'w')
target.write(str(i))
sleep(1)
if __name__ == "__main__":
thread = Thread(target = upfunction, args = (10, ))
thread.start()
print(getstatus())
while getstatus() != "3":
print("NOT 3 ")
sleep(0.5)
continue
thread.stop()
print("thread finished...exiting")
It shows
AttributeError: 'Thread' object has no attribute 'stop'
Please see me as newbie to python. Any help will be highly appreciated
Upvotes: 4
Views: 16213
Reputation: 544
'Thread' object has no attribute 'stop' is helpful answer from python interpretator to you
You should place thread termination condition to upfunction.
def upfunction(arg):
i = 0
while getstatus() != "3":
print ("backup running")
print(getstatus())
target = open(filename, 'w')
target.write(str(i))
i += 1
sleep(1)
if __name__ == "__main__":
thread = Thread(target = upfunction, args = (10, ))
thread.start()
print(getstatus())
print("thread finished...exiting")
Upvotes: 3
Reputation: 547
Here are some explanation about the right way to do that: Is there any way to kill a Thread in Python?.
And as Lex said [0], you can add a condition (in upfunction
arguments) to stop your target function.
Upvotes: 0
Reputation: 9
you can just use threading deamon method to kill this new thread.
thread.start()
thread.deamon()
when the main threads ends this custom threads also dies .so there is no need of that.
Upvotes: 1