我有一小段代碼用於測試,希望能夠調試該問題,而無需修改我的主要applet中的代碼。這已經讓我建立這個代碼:在Python線程中執行多個stdout w/flush
#!/usr/bin/env python
import sys, threading, time
def loop1():
count = 0
while True:
sys.stdout.write('\r thread 1: ' + str(count))
sys.stdout.flush()
count = count + 1
time.sleep(.3)
pass
pass
def loop2():
count = 0
print ""
while True:
sys.stdout.write('\r thread 2: ' + str(count))
sys.stdout.flush()
count = count + 2
time.sleep(.3)
pass
if __name__ == '__main__':
try:
th = threading.Thread(target=loop1)
th.start()
th1 = threading.Thread(target=loop2)
th1.start()
pass
except KeyboardInterrupt:
print ""
pass
pass
我這段代碼的目標是能夠同時擁有這些線程在同一時間標準輸出格式(帶沖洗)顯示輸出,並具有然後並排或者其他的東西。問題是我假設它正在刷新每一個,它默認刷新另一個字符串。如果甚至有可能,我不知道如何讓這個工作。
如果你只是運行其中一個線程,它工作正常。不過,我希望能夠在終端輸出中同時運行兩個線程,並使用自己的字符串同時運行。這裏是一個圖片顯示什麼我越來越:
終端截圖
讓我知道如果你需要更多的信息。提前致謝。
打印到標準輸出不是線程安全的。使用'logging'模塊,實現某種鎖定,或將打印移動到另一個線程。 – Blender
我使用stdout是因爲我喜歡它將如何顯示(例如)一個數字,然後刷新它並在舊的地方打印一個新數字。因此,爲輸出創建一個固定位置,而不是爲每個數字創建一個新行以便打印它。 – BlackVikingPro