【发布时间】:2017-09-30 13:48:24
【问题描述】:
我有一个程序可以通过 API 自动创建 Github 问题。它适用于 Python 2.7,但是当我使用 Python 3 运行它时,出现以下错误:
Traceback (most recent call last):
File "/home/baal/bin/python/zeus-scanner/var/auto_issue/github.py", line 92, in request_issue_creation
urllib2.urlopen(req, timeout=10).read()
File "/usr/lib/python3.5/urllib/request.py", line 163, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python3.5/urllib/request.py", line 464, in open
req = meth(req)
File "/usr/lib/python3.5/urllib/request.py", line 1183, in do_request_
raise TypeError(msg)
TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.
我有以下方法会创建一个 github 问题(在 python 2 中成功,在 python 3 中不成功):
def request_issue_creation():
logger.info(set_color(
"Zeus got an unexpected error and will automatically create an issue for this error, please wait..."
))
def __extract_stacktrace(file_data):
logger.info(set_color(
"extracting traceback from log file..."
))
retval, buff_mode, _buffer = [], False, ""
with open(file_data, "r+") as log:
for line in log:
if "Traceback" in line:
buff_mode = True
if line and len(line) < 5:
buff_mode = False
retval.append(_buffer)
_buffer = ""
if buff_mode:
if len(line) > 400:
line = line[:400] + "...\n"
_buffer += line
return "".join(retval)
logger.info(set_color(
"getting authorization..."
))
encoded = __get_encoded_string()
n = get_decode_num(encoded)
token = decode(n, encoded)
current_log_file = get_latest_log_file(CURRENT_LOG_FILE_PATH)
stacktrace = __extract_stacktrace(current_log_file)
issue_title = stacktrace.split("\n")[-2]
issue_data = {
"title": issue_title,
"body": "Error info:\n```{}````\n\n"
"Running details:\n`{}`\n\n"
"Commands used:\n`{}`\n\n"
"Log file info:\n```{}```".format(
str(stacktrace),
str(platform.platform()),
" ".join(sys.argv),
open(current_log_file).read()
),
}
try:
req = urllib2.Request(
url="https://api.github.com/repos/<API-REPO>/issues", data=json.dumps(issue_data),
headers={"Authorization": "token {}".format(token)}
)
urllib2.urlopen(req, timeout=10).read()
logger.info(set_color(
"issue has been created successfully with the following name '{}'...".format(issue_title)
))
except Exception as e:
logger.exception(set_color(
"failed to auto create the issue, got exception '{}', "
"you may manually create an issue...".format(e), level=50
))
我在网上看到将字符串编码为utf-8 将解决问题,但我不确定这是否可行?任何帮助将不胜感激,谢谢。
【问题讨论】:
标签: python python-2.7 python-3.x compatibility