2010-07-01 52 views
0

這裏沒有傾倒的代碼音調是具有螺紋,所有運行相同類型的對象的各種方法的症狀添加尾隨逗號到打印命令使線程執行了「串行」

。 的方法中,我有一個打印一行字:

print self.args, self.foo

一切工作就好了。

但是,如果我把那行成:

# remain in the same line

print self.args, self.foo,

執行以連載的方式被執行,直到其完成做,好像是print語句塊的其他線程。

import threading, time 

class Graph2(object): 
    def __init__(self, instanceName): 
     self.instanceName = instanceName 

    def __getattr__(self, name): 
     def foo(): 
      for i in xrange(10): 
       #### the tricky line #### 
       # print i, self.instanceName 
       print i, self.instanceName, 
       time.sleep(1) 

     return foo 


class GraphThread(threading.Thread): 
    def __init__(self, graph, method, *args): 
     threading.Thread.__init__(self) 
     self.g, self.m, self.args = graph, method, args 
     self.results = None 

    def run(self): 
     print 'm=%s, args=%s' % (self.m, self.args) 
     self.results = getattr(self.g, self.m)(*self.args) 
     print "...done running method %s, with args %s:"%(self.m,self.args) 

methods = ["degree","betweenness","closeness","cocitation","shell_index","evcent","eccentricity","constraint"] 
threads=[] 

# spawn a new thread for every requesting url 
for method in methods: 
    print "starting thread for method %s..."%method 
    t=GraphThread(Graph2(method),method) 
    t.start() 
    print "..appending thread..." 
    threads.append(t) 
    print "...thread appendd." 
+1

不是出了什麼普遍觀察到後沖洗stdout - 相反一個經常聽到的抱怨是,從不同的線程'print'語句得到所有混合起來。什麼平臺,操作系統和版本,Python版本等? – 2010-07-01 20:28:58

+0

tzury @ x200:〜$ python --version Python 2.6.5 tzury @ x200:〜$ uname -a Linux x200 2.6.32-23-generic#37-Ubuntu SMP Fri Jun 11 08:03:28 UTC 2010 x86_64 GNU/Linux – 2010-07-02 04:10:24

回答

1

嘗試打印

sys.stdout.flush()