我正在使用 python 中的多處理,但我不知道如何啟動執行緒并繼續代碼。
該代碼應檢查是否已將新專案添加到記事本檔案中。如果是,則應等待 2 分鐘,然后將其洗掉。我希望這個洗掉程序是分開的,因為在這 2 分鐘內,可以將一個專案添加到記事本檔案中(這是由我已經撰寫的另一個程式完成的)。基本上,對于添加到記事本檔案的每個新專案,我都想啟動一個新執行緒,該執行緒將在 2 分鐘后洗掉該專案。
這是我所擁有的:
import time
import threading
a_file = open("file.txt", "r")
lines = a_file.readlines()
a_file.close()
a=len(lines)#the initial number of lines
n=0
def delete(a):#the function which deletes the new item
a_file = open("file.txt", "r")
lines = a_file.readlines()
a_file.close()
del lines[a-1]# becasue of indexing it should delete the a-1 element in the list
new_file = open("file.txt", "w ")
for line in lines:
new_file.write(line)
new_file.close()
a=a-1#decreases a so that the function isn't called again
while n==0:
time.sleep(7)
a_file = open("file.txt", "r")
lines = a_file.readlines()
a_file.close()
b=len(lines)#the new number of lines
if b>a:
a=b
t1=threading.Thread(target=delete(a))#the thread
任何幫助,將不勝感激!
uj5u.com熱心網友回復:
為什么不使用Timers 而不是使用Threads?
嘗試運行它,看看它做了什么:
from threading import Timer
def spong(what):
print(what)
Timer(4.0, spong, args=("four point oh",)).start()
Timer(6.0, spong, args=("six point oh",)).start()
Timer(2.0, spong, args=("two point oh",)).start()
print("And, they're off!")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/433431.html
標籤:Python 多线程 python-多处理
