2014-01-30 46 views
1

我正在運行這個腳本,但我似乎無法讓它工作的任何想法?我運行它像python filename.py 10 10,但它返回與「線程錯誤」,它假設打印我假設它是在代碼中。我怎樣才能解決這個問題?Python線程錯誤,抽動腳本

import requests 
import subprocess 
import json 
import sys 
import threading 
import time 
from Queue import Queue 

numberOfViewers = int(sys.argv[1]) 
builderThreads = int(sys.argv[2]) 
startTime = time.time() 
numberOfSockets = 0 
concurrent = 25 
urls = [] 
urlsUsed = [] 

def getURL(): # Get tokens 
    output = subprocess.Popen(["livestreamer", "twitch.tv/The_XPZ", "-j"],  stdout=subprocess.PIPE).communicate()[0] 
    return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter 

def build(): # Builds a set of tokens, aka viewers 
    global numberOfSockets 
    global numberOfViewers 
    while True: 
     if numberOfSockets < numberOfViewers: 
      numberOfSockets += 1 
      print "Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers) 
      urls.append(getURL()) 

def view(): # Opens connections to send views 
    global numberOfSockets 
    while True: 
     url=q.get() 
     requests.head(url) 
     if (url in urlsUsed): 
      urls.remove(url) 
      urlsUsed.remove(url) 
      numberOfSockets -= 1 
     else: 
      urlsUsed.append(url) 
     q.task_done() 

if __name__ == '__main__': 
    for i in range(0, builderThreads): 
     threading.Thread(target = build).start() 

    while True: 
     while (numberOfViewers != numberOfSockets): # Wait until sockets are built 
      time.sleep(1) 

     q=Queue(concurrent*2) 
     for i in range(concurrent): 
      try: 
       t=threading.Thread(target=view) 
       t.daemon=True 
       t.start() 
      except: 
       print 'thread error' 
     try: 
      for url in urls: 
       print url 
       q.put(url.strip()) 
       q.join() 
     except KeyboardInterrupt: 
      sys.exit(1) 

Traceback screenshot

+0

你能給我們完整的追溯? – jayelm

+0

原始代碼在這裏https://gist.github.com/Xeroday/6468146/raw/1b7fb468551a4ba5b73ea3c0b7bc47591c3a8c51/Twitch.py​​ – XPZ

+0

在嘗試運行腳本時,您會收到完整的錯誤消息。 – jayelm

回答

0

你沒有遇到一個錯誤與Threading實現,至少現在。問題是你的try/except塊捕獲每一種類型的錯誤,並打印「線程錯誤」,無論它是什麼。

subprocess.Popen不適用於開放網址。由於您指定的URL /網絡信息不是本地文件或有效命令,因此Windows發生錯誤。

相反,您需要查看像urllib2Requests這樣的庫,以便通過HTTP請求獲取信息。假設您期待json數據,您可以使用json庫對其進行解碼。因此,例如:

import urllib2 

def getURL(): 
    output = urllib2.urlopen('http://www.twitch.tv/The_XPZ') # Any URL 
    return json.load(response)['streams']['worst']['url'] 

從代碼中不清楚您要訪問的URL是什麼,但您可以替換您所需的。