天天看点

python 2.7 中文编码

python 2.7 中文编码

文件编码 "-- coding:utf-8 --"

  • 文件编码的意思是,以“utf-8”为例,在当前文件中,可以存在“utf-8”的中文字符,如下例子,如果控制台是utf-8编码的,那就会输出“你好世界! hello world ”
# -*- coding:utf-8 -*-
    def test3():
        str1 = u"你好世界! "
        str2 = u"hello world "
        print str1+str2
    test3()
           

字符编码

  • 如果控制台是gbk上,则会输出乱码,如何解决呢?下面代码:
# -*- coding:utf-8 -*-
    def test3():
        str1 = u"你好世界! "
        str2 = u"hello world "
        print (str1+str2).encode("gbk")
    test3()
           
  • 如果你的python程序读进来的系统路径是gbk编码的(比如:你的python程序在windows默认编码gbk下,命令行接受了一个中文路径的参数;或者你的python代码中读取了一个用户的环境变量,这个环境变量中带中文,如何让代码识别这个路径呢?)请看下面代码:
# -*- coding:utf-8 -*-
    def test1():
        user_tmp = os.getenv("tmp")//C:\Users\测试1\AppData\Local\Temp
        file_dir = os.path.join(user_tmp.decode("gbk"), "update_dir")
        os.mkdir(file_dir)
    test1()
           

有些程序代码可能需要如下改动

# -*- coding:utf-8 -*-
def test3();
    user_tmp = os.getenv("tmp") //C:\Users\测试1\AppData\Local\Temp
    file_dir = os.path.join(user_tmp.decode("gbk"), "updatedir")
    deploy_path = os.path.join(file_dir, "deploy.exe")
    cmd = "\"%s\"" % deploy_path
    p = subprocess.Popen(cmd.encode("gbk"), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
test3()