2017-08-03 59 views
1

嗨,我遇到了此錯誤消息的問題。我對Python很陌生,這個Python2和Python3是一個麻煩。我不確定這裏要做什麼,錯誤信息如下所示。TypeError:需要類似字節的對象,而不是'str' - python 2至3

Using Ticker: AAPL 
    Traceback (most recent call last): 
     File "realtime.py", line 18, in <module> 
     r=requests.get(auth_url, headers={"Authorization": "Basic %s" % base64.b64encode(os.environ['INTRINIO_USER'] + ":" + os.environ['INTRINIO_PASSWORD'])}) 
     File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\base64.py", line 58, in b64encode 
     encoded = binascii.b2a_base64(s, newline=False) 
    TypeError: a bytes-like object is required, not 'str' 

我使用的代碼如下所示。

import websocket 
import _thread 
import time 
import requests 
import base64 
import json 
import sys 
import os 
from requests.auth import HTTPBasicAuth 

try: 
    print ("Using Ticker: " + str(sys.argv[1])) 
except: 
    print ("Please include ticker as first argument") 
    sys.exit() 

auth_url = "https://realtime.intrinio.com/auth"; 
r=requests.get(auth_url, headers={"Authorization": "Basic %s" % base64.b64encode(os.environ['INTRINIO_USER'] + ":" + os.environ['INTRINIO_PASSWORD'])}) 

socket_target = "wss://realtime.intrinio.com/socket/websocket?token=%s" % (r.text) 

def on_message(ws, message): 
    try: 
     result = json.loads(message) 
     print (result["payload"]) 
    except: 
     print (message) 

def on_error(ws, error): 
    print ("###ERROR### " + error) 

def on_close(ws): 
    print ("###CONNECTION CLOSED###") 

def on_open(ws): 
    def run(*args): 
     security = "iex:securities:" + str(sys.argv[1]).upper() 
     message = json.dumps({"topic": security,"event": "phx_join","payload": {},"ref": "1"}) 
     ws.send(message) 
    thread.start_new_thread(run,()) 


websocket.enableTrace(True) 
ws = websocket.WebSocketApp(socket_target, on_message = on_message, on_error = on_error, on_close = on_close) 
ws.on_open = on_open 
ws.run_forever() 
+0

相關:https://stackoverflow.com/questions/21689365/python-3-typeerror-must-be-str-not-bytes-with-sys-stdout-write – bipson

+0

我不知道在哪裏雖然 –

+0

您正在向''base64.b64encode()''傳遞一個字符串''os.environ ['INTRINIO_USER'] +「:」+ os.environ ['INTRINIO_PASSWORD']'',對吧? – bipson

回答

1

你應該編碼strbytes

data_str = os.environ['INTRINIO_USER'] + ":" + os.environ['INTRINIO_PASSWORD'] 

data_bytes = data.encode("utf-8") 

base64.b64encode(data_byte) 
相關問題