正如我在標題中所說,我想創建string variables使用. 并使用刪除它們。Threadsinputflag我需要一步步解釋這個問題。比方說,我input從用戶那里得到。這input由用戶將是 的名稱Thread variable。讓input等于love和like。在這種情況下,將創建 2 個線程變量和線程。他們的名字將是loveand like。要創建一個Thread,必須給出這樣的代碼。代碼:from threading import Threadimport timeimport re# Using while loop. Because I want to create multiple Threads by doing this.# Dictsdicts = {}flags = {}while True: # Input threadName = input('Thread name please? ') # To delete a Thread if 'delete' in threadName: delThread = re.search(r'delete (.*)', threadName) if delThread: delThread = list(map(str, delThread.groups())) delThread = ''.join(delThread) print('DELETING:', delThread) flags[delThread] = True print('DICT NOW:', flags) else: # Target function for every Thread. Print a message every 3 secs. def targetfunc(tname): while True: if flags[tname] in flags and flags[tname] == True: break print(f"I'm {tname} Thread.") time.sleep(3) # Create Threads. 'dicts[threadName]' will be whatever the user enters input. # Should be string variable. # 'threadName' is equal to input too. dicts[threadName] = Thread(target = targetfunc, args = [threadName]) dicts[threadName].start() flags[threadName] = False print(dicts) print(flags)我正在使用 2 個字典。一個dicts用于創建Threads,另一個用于使用刪除它們flag。要創建,只需鍵入您要調用的線程即可。要刪除,請鍵入delete (thread name)。KeyError當我嘗試刪除時,此代碼會為每個線程拋出。這是完整的錯誤。這就是程序。如何解決這個問題?我想要實現的是:當我鍵入名稱時,該名稱必須創建一個Thread具有該名稱的新名稱。但是當我輸入時delete (thread name)應該停止(thread name) Thread。我希望我能解釋清楚。希望你幫忙。
1 回答

繁星coding
TA貢獻1797條經驗 獲得超4個贊
問題是您正在檢查字典條目而不是檢查該鍵是否存在。
更改此行:
if flags[tname] in flags and flags[tname] == True:
對此:
if tname in flags and flags[tname] == True:
通過此更改,代碼可以正確運行。
添加回答
舉報
0/150
提交
取消