2017-03-14 22 views
0

我試圖將stdout保存到python中的變量。我當前的解決方案在python shell中工作正常,但是當作爲腳本運行時,它會出錯。這是我目前的測試代碼:將python stdout保存到一個變量在python shell中工作,但不能作爲腳本

import yaml 
    import sys 
    from slackclient import SlackClient 
    from io import StringIO # Python3 
    slack_token = "SOME TOKEN HERE" 
    sc = SlackClient(slack_token) 
    old_stdout = sys.stdout 
    result = StringIO() 
    sys.stdout = result 
    row_message = '[{"title": "Test", "pretext": "this is an example   message!", "text": "Super Awesome Test!"}]' 
    sc.api_call(
     "chat.postMessage", 
     channel="#channel_name", 
     username="My User", 
     icon_url="http://some.url.here/", 
     attachments=row_message 
    ) 
    sys.stdout = old_stdout 
    result_string = result.getvalue() 
    example = yaml.load(result_string)['ts'] 
    print(example) 

我在Python外殼輸出的是我期望:

>>> print(example) 
    1489460593.207577 
    >>> 

但是當我保存代碼並運行它作爲腳本:

# ./test 
    Traceback (most recent call last): 
     File "./test", line 22, in <module> 
     example = yaml.load(result_string)['ts'] 
    TypeError: 'NoneType' object is not subscriptable 

任何人都可以啓發我爲什麼這個工程在python shell而不是腳本?我能做些什麼來完成這項工作?謝謝。

+0

沒有什麼是在標準輸出,因爲沒有打印。可能Slack返回字符串,不打印它。它會在解釋器中打印出來,因爲那就是解釋器對結果做了什麼,不會在某處保存。如果你刪除stdout swap,會發生什麼?值是否打印?我的猜測不是。只需將其直接保存到一個變量中,並停止與stdout混淆。 – zstewart

回答

1

謝謝@zstewart,你說得對。我只是過分複雜。這是我正在做的。

 response = sc.api_call("chat.postMessage", channel="#channel", username="username", icon_url="http://some.url.here", attachments=row_message) 
     thread_val_list = [ val for key,val in response.items() if key=='ts' ] 
     thread_val = "".join(thread_val_list) 
相關問題