---
title: "Python2.7解决中文的方法"
author: "listen-raining"
date: "2017-07-21T16:49:43Z"
tags: []
categories: ["编程语言"]
slug: "python2-7"
draft: false
lastmod: "2017-07-21T16:59:33Z"
id: 2386335
url: "https://listen-raining.iteye.com/blog/2386335"
---

Python2.7 的中文乱码还是挺恶心人的。

解决方法一：
       在文件 D:\Python27\Lib\ntpath.py 中加入如下代码：
                import sys
                reload(sys)
                sys.setdefaultencoding('cp936')


对于读取命令返回值时还得需要解码：

p = subprocess.Popen('ipconfig /all', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
s = ' '.join(p.stdout.readlines())
return p.wait(),s.encode('utf8')  #对于读取的命令返回值需要进行解码




解决方案二：

在脚本中加入如下代码：
import sys
reload(sys)
sys.setdefaultencoding('cp936')

注意：sys模块只有先加载，才能使用setdefaultencoding()方法；



------------------------


2017-07-21

43F.dianxinguangchang.yuexiuqu.guangzhoushi.guangdongsheng