2013-04-25 81 views
0

我需要幫助來從pycurl獲取輸出,我試圖在子進程中運行。我試圖把這個輸出放入一個隊列中,而不是把這個隊列放在另一個類中。在一個單獨的線程中的pycurl子進程

不幸的是,現在我有沒有輸出=(

import threading 
import random 
import time 
import Queue 
import urllib2 
import sys 
import simplejson, pycurl 
import sys, signal 

queue = Queue.Queue() 
keep_running = True 
user = "username" 
pswd = "pass" 

class MyThread(threading.Thread): 
    def __init__(self, queue): 
     threading.Thread.__init__(self) 
     self.queue = queue 

    def run(self): 
     curl_path = '/usr/bin/curl' 
     curl_list = [curl_path] 
     args = ('curl', 'https://stream.twitter.com/1/statuses/filter.json?track=java', '-u', 'user:pass') 
     for arg in args: 
      curl_list.append(arg) 
      child = subprocess.Popen(
         curl_list, 
         shell=False, 
         #stdout=subprocess.PIPE) 
         stderr=subprocess.PIPE) 
      try: 
       out += child.communicate() 
       c_out.write(out) 
       self.queue.put(c_out) 
       self.queue.task_done() 
      except KeyboardInterrupt: 
       child.kill() 


class Starter(): 
    def __init__(self): 
     self.queue = queue 
     t = MyThread(self.queue) 
     t.daemon=True 
     t.start() 
     self.next() 

    def next(self): 
     while True: 
      time.sleep(0.5) 
      if not self.queue.empty(): 
       line = self.queue.get(timeout=0.2) 
       print '\n\nIM IN STARTER %s' % line 
      else: 
       print 'waiting for queue' 

def main(): 
    try: 
     Starter()  
    except KeyboardInterrupt, e: 
     print 'Stopping' 
     raise 

main() 

回答

1

你似乎混淆你的參數子過程很有點...的的args列表應該是所有不同的部分命令的那你會使用捲曲,你正在把它們都聚集在這是不會與子工作的方式。你應該curl_list看起來更像這個...

curl_path = '/usr/bin/curl' 
curl_list = [curl_path, 'https://stream.twitter.com/1/statuses/filter.json?track=java', '-u', 'user:pass'] 

您同時還使用了不必要的此刻......你不想在這個列表中循環你只是想將它傳遞給子進程,這將適當地處理它。而且你也希望stdout從中得到結果,所以你也需要在其中包含管道。

即,整個事情應該是...

def run(self): 
    curl_path = '/usr/bin/curl' 
    curl_list = [curl_path, 'https://stream.twitter.com/1/statuses/filter.json?track=java', '-u', 'user:pass'] 

    child = subprocess.Popen(curl_list, 
          shell=False, 
          stdout=subprocess.PIPE, 
          stderr=subprocess.PIPE) 
    try: 
     out += child.communicate()[0] 
     c_out.write(out) 
     self.queue.put(c_out) 
     self.queue.task_done() 
     except KeyboardInterrupt: 
      child.kill() 

可能要考慮再看看subprocess documentation更好地理解上述的變化。我實際上並沒有通過口譯員來解決這個問題,所以它可能並不完美,但應該讓你朝着正確的方向前進......祝你好運!

+0

非常感謝您的回覆,您可以幫我多做一件事:我忘記了包含該變量'c_out'被定義爲'c_out = cStringIO.StringIO()',但是當我運行您的代碼時,我仍然在隊列中沒有任何東西 – Vor 2013-04-25 14:38:40

+0

你爲什麼使用cStringIo?我不確定那是什麼......你應該能夠將字符串添加到隊列中。 – EEP 2013-04-25 15:14:59

+0

我嘗試了你沒有使用cString的建議,只是把'out'放入隊列中,但後來當我檢查隊列時,它沒有向我顯示任何東西。我的意思是它表明它是空的 – Vor 2013-04-25 15:18:38