Python2 常见问题

Python编程时遇到过一些问题,整理了以下内容,含解决办法。

1、SyntaxError: Non-ASCII character ‘\xe4’ in file
文件中出现了中文,且没有编码声明,Python2将默认以ASCII作为标准编码,而Python2支持的ASCII码无中文。

解决方法:

必须在文件中第一行声明文件编码

# -*- coding: utf-8 -*-

2、UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-1: ordinal not in range
此问题常见于Python2环境中。

解决方法:

import sys

# Python2.x
reload(sys)
sys.setdefaultencoding("utf8")

3、Python2写文件中文乱码
Python2中open方法是没有encoding这个参数的,如果像python3一样的写法会报异常:
TypeError: ‘encoding’ is an invalid keyword argument for this function

解决方法:

# -*- coding: utf-8 -*-

import io

test_1 = "中文"
with io.open("test.txt", "w", encoding="utf-8") as f:
    f.write(unicode(test_1, "utf-8"))

with open("test.txt", "r") as f:
    test_2 = unicode(f.read(), "utf-8")
    print test_2

4、Mac上PyCharm运行多进程报错的解决方案
运行时报错运行时报错
may have been in progress in another thread when fork() was called. We cannot safely call it or ignore it in the fork() child process. Crashing instead. Set a breakpoint on objc_initializeAfterForkError to debug.

解决方案

添加环境变量:

点击窗口上的Run->Edit Configurations...->Environment variables->点击输入栏后的文件夹图标

添加内容:

key: OBJC_DISABLE_INITIALIZE_FORK_SAFETY, value: YES

完整示例:

OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值