我有這段代碼通過運行後臺進程來獲取推文。以下腳本使用subprocess.Popen
函數從主腳本運行。這樣主腳本將在調用後臺進程腳本後停止執行。主腳本停止後臺進程無效的參數錯誤
def start_listner(unique_id, keyword, limit=200):
class CustomStreamListener(tweepy.StreamListener):
def __init__(self, api):
logger.info('runnning')
self.api = api
super(tweepy.StreamListener, self).__init__()
#setup rabbitMQ Connection
def on_status(self, status):
print status.text.encode('utf-8'), "\n"
#queue the tweet and writes the tweet to the log
def on_error(self, status_code):
#some code to not kill the stream
def on_timeout(self):
#some code to not kill the stream
sapi = tweepy.streaming.Stream(auth, CustomStreamListener(api))
try:
logger.info('tracking started')
logger.info(keyword)
logger.info(type(keyword))
kw = keyword
sapi.filter(track=[kw]) # keeps listening to the streaming api
except Exception, err:
logger.info(kw) # fails at this place when main py stops
logger.info(err)
if __name__ == "__main__":
logger.info("just now started")
try:
a = str(sys.argv[1])
b = str(sys.argv[2])
#c = int(sys.argv[5])
logger.info(a)
logger.info(b)
except Exception, err:
logger.info("inside main")
start_listner(a, b)
按照最高的投票答案here我用下面的主函數來調用StreamingAnalytics.py(上面的代碼)
import time
import subprocess
subprocess.Popen(["python", "StreamingAnalytics.py", 'SriLankaQ', 'lanka'])
print 'I could escape.........'
time.sleep(15)
我添加了一個睡眠所以鳴叫將被成功添加到在此期間的RabbitMQ隊列。但是一旦主腳本停止後臺進程,就會輸出以下錯誤。
2015年12月22日16:28:16559 - 主 - INFO - { '文本':「RT @Dory:蘭卡 歌唱熱線bling的\ XF0 \ x9f \ X98 \ X82 \ XF0 \ x9f \ X98 \ X82 '源':u'Twitter的iPhone'}
2015年12月22日16:28:17752 - 主 - INFO - 蘭卡
2015年12月22日16時28分:17,752 - main - INFO - [Errno 22]無效的參數
UPDATE: 因爲我認爲它在傳遞參數的問題,我通過主腳本將它們寫入文件和讀取從後臺進程文件的文件刪除使用的參數。所以,
subprocess.Popen(["python", "StreamingAnalytics.py"])
但仍然是相同的錯誤來。使用回溯模塊,我可以打印關於此錯誤的更多信息。
2015-12-24 11:01:16,562 - __main__ - INFO - Traceback (most recent call last):
File "StreamingAnalytics.py", line 84, in <module>
sapi.filter(track=[keyword])
File "C:\Python27\lib\site-packages\tweepy\streaming.py", line 445, in filter
self._start(async)
File "C:\Python27\lib\site-packages\tweepy\streaming.py", line 361, in
_start
self._run()
File "C:\Python27\lib\site-packages\tweepy\streaming.py", line 294, in _run
raise exception IOError: [Errno 22] Invalid argument
所以我不得不修改af事實上,但[我的例子](https://gist.github.com/waynew/c47fe03405e451709906)對我來說工作得很好。它也適用於你嗎?我有你的第一個例子啓動程序運行它(即'subprocess.Popen([「python」,「StreamingAnalytics.py」,'SriLankaQ','lanka'))') –
你可以讓你的'StreamingAnalytics.py'運行直接調用它而不使用'subprocess.Popen'? (即在終端中調用'python StreamingAnalytics.py') – Jon
@WayneWerner它現在可以工作!我在'on_status'函數中有一個打印語句當我刪除它的時候它工作。我把這也包括在我的問題中。我認爲問題在於此。無論如何,它的答案引導我去做這件事。如果您將其添加爲答案,並說明爲何它在刪除打印時起作用。我很樂意接受它作爲正確的答案。 –