2017-03-14 2 views
0

私はstdoutをPythonの変数に保存しようとしています。私の現在の解決策はPythonシェルでうまく動作しますが、スクリプトとして実行するとエラーになります。私は、コードを保存し、スクリプトとして、それを実行したときに変数へのpythonのstdoutの保存は、スクリプトとしてではなく、Pythonシェルで動作します。

>>> print(example) 
    1489460593.207577 
    >>> 

:しかしPythonシェルで

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) 

私の出力は、私が期待するものである:ここに私の現在のテストコードがある

# ./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シェルで動作するのかスクリプトではないのかを教えてもらえますか?私はこの仕事をしようとすることができますか?ありがとう。

+0

何も印刷されていないため、何も出力されません。おそらくSlackは文字列を返し、印刷しません。通訳者がどこかで救われない結果になるので、それは通訳者に印刷されます。 stdoutスワップを削除すると、どうなりますか?値は印刷されますか?私の推測ではありません。単に変数に直接保存して、stdoutを使っていこうとしないでください。 – zstewart

答えて

1

ありがとう@zstewart、あなたは正しいです。私はちょうどそれをovercomplicatedしていた。ここに私が代わりにやっていることがあります。

 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) 
関連する問題