2017-02-27 100 views
1

我正嘗試使用cygwin來運行我的Python代碼。該腳本應該啓動一個線程並對其進行處理。但它以某種方式不起作用。作爲一個最小的例子,我使用這裏的代碼'http://www.saltycrane.com/blog/2008/09/simplistic-python-thread-example/'。 正如你可以在下面的日誌中看到的,Thread.start()在cygwin中結束Pyhton交互式輸入,沒有任何消息。 相反,在另一臺機器上,程序按預期運行。我期待cygwin問題,但在cygwin上重新安裝Python軟件包並沒有幫助。Python線程無法在cygwin上運行

想法?

$ python 
Python 2.7.12 (default, Oct 10 2016, 12:56:26) 
[GCC 5.4.0] on cygwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import time 

def myfunc(i): 
    print "sleeping 5 sec from thread %d" % i 
    time.sleep(5) 
    print "finished sleeping from thread %d" % i 

for i in range(10): 
    t = Thread(target=myfunc, args=(i,)) 
    t.start() 
>>> from threading import Thread 
>>> 
>>> def myfunc(i): 
...  print "sleeping 5 sec from thread %d" % i 
...  time.sleep(5) 
...  print "finished sleeping from thread %d" % i 
... 
>>> for i in range(10): 
...  t = Thread(target=myfunc, args=(i,)) 
...  t.start() 
... 

[email protected]~ 
$ 

回答

0

改寫這樣
cat prova-python.py

#!/usr/byn/python 
import time,threading 

def myfunc(i): 
    print "sleeping 5 sec from thread %d" % i 
    time.sleep(5) 
    print "finished sleeping from thread %d" % i 

for i in range(10): 
    t = threading.Thread(target=myfunc, args=(i,)) 
    t.start() 

作品,但第二階段的輸出可以線程之間的重疊。

$ python prova-python.py 
sleeping 5 sec from thread 0 
sleeping 5 sec from thread 1 
sleeping 5 sec from thread 2 
sleeping 5 sec from thread 3 
sleeping 5 sec from thread 4 
sleeping 5 sec from thread 5 
sleeping 5 sec from thread 6 
sleeping 5 sec from thread 7 
sleeping 5 sec from thread 8 
sleeping 5 sec from thread 9 
finished sleeping from thread 0 
finished sleeping from thread 2 
finished sleeping from thread 1 
finished sleeping from thread 3 
finished sleeping from thread 4 
finished sleeping from thread 5 
finished sleeping from thread 6 
finished sleeping from thread 9finished sleeping from thread 8finished sleeping from thread 7 
+0

好吧,我的錯,我沒有說清楚,但它是一個cygwin問題!我發佈的程序也適用於另一臺機器。 - >調整問題... – Mario

+0

我的版本在cygwin python上運行。你測試過了嗎?缺少「導入時間,線程」和「threading.Thread」導致執行錯誤。 – matzeri

+0

運行它我得到了一個語法錯誤,因爲'%i'\ n''。解決這個問題後,腳本運行時沒有任何輸出... – Mario