0

私はPythonスレッドの問題があります。私は一日以上見渡してきましたが、それ以上は改善されないので、私は助けを求めることを考えました。私はpython3.4を使用します。Pythonスレッドの実行はどのように引数を実行しますか?

class myThread (threading.Thread): 
    def __init__(self, url): 
     threading.Thread.__init__(self) 
     self.url = url 
    def run(self): 
     spider (url) 

と私はコード内のいくつかの部分にtoBeProcessed +'/robots.txt'を使用しています: 最初の質問は違いどうなるかです。上記の方法を使用した場合、エラーは発生しませんが、それでもすべてのスレッドが実行されるわけではありません。私は、以下の方法を使用した場合、それは私に語ったものの、それunsupported operand type(s) for +: '_thread._local' and 'str':私は

def run(self): 
    spider (self.url) 

(注)この宣言toBeProcessed = threading.local()を持っています。

2番目の質問は残りのコードについてですが、2つのスレッドだけが作業を行い、残りのスレッドは番号が何であれ動作しません。

全コード:

def spider(url,superMaxPages): 
    print(threading.current_thread()) 
    toBeProcessed = threading.local() 
    data = threading.local() 
    parser = threading.local() 
    links = threading.local() 
    lock = threading.Lock() 
    writeLock = threading.Lock() 

    # Start from the beginning of our collection of pages to visit: 
    while 1: 
     if LinkParser.numVisited > maxPages: 
      print ('max pages reached') 
      break 

     lock.acquire() 
     try: 
      if not url: 
       time.sleep(0.01) 
       lock.release() 
       continue 
      print('to be processed ') 
      toBeProcessed = url.pop() 
     except: 
      print('threading error') 
     lock.release() 
     # In case we are not allowed to read the page. 
     rp = robotparser.RobotFileParser() 
     rp.set_url(toBeProcessed +'/robots.txt') 
     rp.read() 
     if not(rp.can_fetch("*", toBeProcessed)): 
      continue 

     LinkParser.visited.append(toBeProcessed) 

     LinkParser.numVisited += 1 

     writeLock.acquire() 
     try: 
      f.write(toBeProcessed+'\n') 
     finally: 
      writeLock.release() 

     try: 
      parser = LinkParser() 
      data, links = parser.getLinks(toBeProcessed)   
      # Add the pages that we visited to the end of our collection 
      url = url + links 
      print("One more page added from &i",threading.get_ident()) 
     except: 
      print(" **Failed!**") 

class myThread (threading.Thread): 
    def __init__(self, url, maxPages): 
     threading.Thread.__init__(self) 
     self.maxPages = maxPages 
     self.url = url 
    def run(self): 
     spider (self.url, maxPages) 

urlがこのurl = [] のように初期化され、これはあなたが間違ってそれをやっている、私は私のスレッドを実行する方法 myThread(spider, (url,maxPages)).start

答えて

0

ではありません。文字列にlocalのインスタンスを連結する必要はありません。あなたはこのようなあなたのlocalインスタンスの属性を格納する必要があります。

import threading 

toBeProcessed = threading.local() 
toBeProcessed.url = url.pop()  
toBeProcessed.url += '/robots.txt' 

また、あなたがあなたの__init__方法でsuper()を使用することを検討すべきです。

+0

AttributeError: 'function'オブジェクトには属性 'pop''がありません –

+0

と 'run(self.url)を使用する場合とは何が違うのですか? 'run(url)'よりも? 'self.url'には –

+0

、' url'はインスタンス変数です。一方、 'run(url)'では、urlは 'run'の単なる引数です。 'url'の種類は何ですか? – styvane

関連する問題