亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何為線程創建字符串變量并使用標志刪除它們

如何為線程創建字符串變量并使用標志刪除它們

繁星點點滴滴 2023-06-20 14:36:49
正如我在標題中所說,我想創建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:

通過此更改,代碼可以正確運行。


查看完整回答
反對 回復 2023-06-20
  • 1 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號