Python设置编码和PYTHONPATH

简介:   Python中的编码是个恼人的问题,第一个是文件编码,在第一行设置了#-*- coding: utf-8 -*-就可以解决。 第二个是环境编码,就是你有个中文unicode的encode或decode操作,它给你报错。

 

Python中的编码是个恼人的问题,第一个是文件编码,在第一行设置了#-*- coding: utf-8 -*-就可以解决。

第二个是环境编码,就是你有个中文unicode的encode或decode操作,它给你报错。

我们最不喜欢看见这段出错信息了:

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

加入这段代码在项目入口文件开头,可以解决这个问题。

import sys
try:
    reload(sys)
    sys.setdefaultencoding("utf-8")
except AttributeError:
    pass  #没起作用

或者将这段代码放在项目根目录下的sitecustomize.py文件中。

问题是python2.5之后的版本,有时不在项目开头自动加载这个文件。纠结啊,自己定义的方式自己有时不支持。

只好在入口文件加一段,确保执行sitecustomize.py

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

#解决Python2.5之后有时无法载入sitecustomize.py的问题
import sys
import os
sys.path = [os.getcwd()] + sys.path
import sitecustomize
reload(sitecustomize)

另外关于python的搜索路径PYTHONPATH,可以用以下方式增加一个路径到其中,比如项目根目录下的library

 

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

import os.path
import sys
import site

try:
    reload(sys)
    sys.setdefaultencoding("utf-8")
except AttributeError:
    pass

base_dir = os.path.dirname(os.path.abspath(__file__))
prev_sys_path = list(sys.path)

# site.addsitedir adds this directory to sys.path then scans for .pth files
# and adds them to the path too.
site.addsitedir(os.path.join(base_dir, 'library'))

# addsitedir adds its directories at the end, but we want our local stuff
# to take precedence over system-installed packages.
# See http://code.google.com/p/modwsgi/issues/detail?id=112
new_sys_path = []
for item in list(sys.path):
  if item not in prev_sys_path:
    new_sys_path.append(item)
    sys.path.remove(item)
sys.path[:0] = new_sys_path
目录
相关文章
|
27天前
|
存储 文件存储 Python
python进制和编码
python进制和编码
|
27天前
|
Java 编译器 C语言
python安装、输入输出、注释、中文编码、编码规范等基础语法
python安装、输入输出、注释、中文编码、编码规范等基础语法
|
2月前
|
Shell Python
python设置应用程序的样式并部署(二)
python设置应用程序的样式并部署(二)
20 0
|
2月前
|
Python
python设置应用程序的样式并部署(一)
python设置应用程序的样式并部署(一)
16 1
|
6天前
|
机器学习/深度学习 数据采集 算法
【Python机器学习专栏】使用Scikit-learn进行数据编码
【4月更文挑战第30天】本文介绍了Python Scikit-learn库在机器学习数据预处理中的作用,尤其是数据编码。数据编码将原始数据转化为算法可理解的格式,包括标签编码(适用于有序分类变量)、独热编码(适用于无序分类变量)和文本编码(如词袋模型、TF-IDF)。Scikit-learn提供LabelEncoder和OneHotEncoder类实现这些编码。示例展示了如何对数据进行标签编码和独热编码,强调了正确选择编码方法的重要性。
|
7天前
|
弹性计算 运维 Shell
设置Python 支持自动命令补齐功能
【4月更文挑战第29天】
6 0
|
8天前
|
弹性计算 运维 Shell
设置 Python 支持自动命令补齐功能
【4月更文挑战第29天】
5 1
|
10天前
|
存储 JSON 数据处理
|
10天前
|
数据采集 自然语言处理 数据挖掘
ftfy,一个超强的 Python 编码问题修复库!
ftfy,一个超强的 Python 编码问题修复库!
8 0
|
12天前
|
存储 编解码 运维
第二章 Python字符串处理和编码不再发愁
第二章 Python字符串处理和编码不再发愁