运行HTMLTestRunner时报错:SyntaxError: Non-ASCII character '\xe8'和UnicodeDecodeError: 'ascii'

在将Python3代码移植到Python2.7时遇到SyntaxError和UnicodeDecodeError。解决方法是在文件开头添加 '# - *- encoding: utf-8 - *-' 并确保对中文字符串使用'u'前缀。
摘要由CSDN通过智能技术生成

源代码如下(源代码本为python3.5.6版本,后面复制到python 2.7版本上运行):

from HTMLTestRunner import HTMLTestRunner
import unittest
import os
import  time

if __name__=='__main__':
    case_path = os.path.join(os.getcwd())
    print case_path
    root_path = os.path.abspath(os.path.dirname(os.getcwd()))
    print root_path
    report_path = os.path.join(root_path, 'report')
    print report_path
    now = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time()))
    report_path1 = os.path.join(report_path, 'autotest_result_' + now + '.html')
    report_file = open(report_path1, "wb")

    runner=HTMLTestRunner(stream=report_file,title=u'自动化测试报告',description=u'测试结果')
    cases = unittest.defaultTestLoader.discover(case_path, pattern='test*.py', top_level_dir=None)
    runner.run(cases)
    report_file.close()

运行以上代码的时候,出现报错:SyntaxError: Non-ASCII character '\xe8'

后来发现用python2.7版本的时候必须在最开头加上:
# - *- encoding: utf- 8 - *-
如果只有# - *- encoding: utf- 8 - *-,没有在中文前面加 u 也是会出现报错的,报错具体如下:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 211: ordinal not in range(128)
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值