Answering this for late-comers because I don't think that the posted answers get to the root of the problem, which is the lack of locale environment variables in a CGI context. I'm using Python 3.2.

  1. open() opens file objects in text (string) or binary (bytes) mode for reading and/or writing; in text mode the encoding used to encode strings written to the file, and decode bytes read from the file, may be specified in the call; if it isn't then it is determined by locale.getpreferredencoding(), which on linux uses the encoding from your locale environment settings, which is normally utf-8 (from e.g. LANG=en_US.UTF-8)

    >>> f = open('foo', 'w')         # open file for writing in text mode
    >>> f.encoding
    'UTF-8' # encoding is from the environment
    >>> f.write('€') # write a Unicode string
    1
    >>> f.close()
    >>> exit()
    user@host:~$ hd foo
    00000000 e2 82 ac |...| # data is UTF-8 encoded
  2. sys.stdout is in fact a file opened for writing in text mode with an encoding based on locale.getpreferredencoding(); you can write strings to it just fine and they'll be encoded to bytes based on sys.stdout's encoding; print() by default writes to sys.stdout - print() itself has no encoding, rather it's the file it writes to that has an encoding;

    >>> sys.stdout.encoding
    'UTF-8' # encoding is from the environment
    >>> exit()
    user@host:~$ python3 -c 'print("€")' > foo
    user@host:~$ hd foo
    00000000 e2 82 ac 0a |....| # data is UTF-8 encoded; \n is from print()

    ; you cannot write bytes to sys.stdout - use sys.stdout.buffer.write() for that; if you try to write bytes to sys.stdout using sys.stdout.write() then it will return an error, and if you try using print() then print() will simply turn the bytes object into a string object and an escape sequence like \xff will be treated as the four characters \, x, f, f

    user@host:~$ python3 -c 'print(b"\xe2\xf82\xac")' > foo
    user@host:~$ hd foo
    00000000 62 27 5c 78 65 32 5c 78 66 38 32 5c 78 61 63 27 |b'\xe2\xf82\xac'|
    00000010 0a |.|
  3. in a CGI script you need to write to sys.stdout and you can use print() to do it; but a CGI script process in Apache has no locale environment settings - they are not part of the CGI specification; therefore the sys.stdout encoding defaults to ANSI_X3.4-1968 - in other words, ASCII; if you try to print() a string that contain non-ASCII characters to sys.stdout you'll get "UnicodeEncodeError: 'ascii' codec can't encode character...: ordinal not in range(128)"

  4. a simple solution is to pass the Apache process's LANG environment variable through to the CGI script using Apache's mod_env PassEnv command in the server or virtual host configuration: PassEnv LANG; on Debian/Ubuntu make sure that in /etc/apache2/envvars you have uncommented the line ". /etc/default/locale" so that Apache runs with the system default locale and not the C (Posix) locale (which is also ASCII encoding); the following CGI script should run without errors in Python 3.2:

    #!/usr/bin/env python3
    import sys
    print('Content-Type: text/html; charset=utf-8')
    print()
    print('<html><body><pre>' + sys.stdout.encoding + '</pre>h€lló wörld<body></html>')

https://stackoverflow.com/questions/9322410/set-encoding-in-python-3-cgi-scripts

彻底解决python cgi 编程出现的编码问题的更多相关文章

  1. Python CGI编程(转自易百)

    Python CGI编程 Python的CGI编程,公共网关接口或CGI,Web服务器和一个自定义的脚本之间交换信息是一组定义的标准.     什么是CGI ? 公共网关接口或CGI,Web服务器和一 ...

  2. python CGI编程-----简单的本地使用(1)

    本章节需要安装python开发工具,window平台安装地址:https://www.python.org/downloads/windows/,linux安装地址:https://www.pytho ...

  3. 转:python cgi编程

    转:http://www.runoob.com/Python/python-cgi.html 什么是CGI CGI 目前由NCSA维护,NCSA定义CGI如下: CGI(Common Gateway ...

  4. 吴裕雄--天生自然python学习笔记:Python CGI编程

    什么是CGI CGI 目前由NCSA维护,NCSA定义CGI如下: CGI(Common Gateway Interface),通用网关接口,它是一段程序,运行在服务器上如:HTTP服务器,提供同客户 ...

  5. python CGI 编程实践

    文章更新于:2020-03-05 注1:安装 python 参见: python 的安装使用和基本语法 注2:配置 web 环境参见: Windows&linux使用集成环境搭建 web 服务 ...

  6. Python CGI编程和CGIHTTPServer

    Python2.7 的CGIHTTPServer 可以作为一个简单的HTTP服务器,能够调用cgi脚本 1 在任意目录下创建一个特殊的目录 cgi-bin ,用于存放自己写的脚本(.py或.cgi) ...

  7. Python基础编程:字符编码、数据类型、列表

    目录: python简介 字符编码介绍 数据类型 一.Python简介 Python的创始人为Guido van Rossum.1989年圣诞节期间,在阿姆斯特丹,Guido为了打发圣诞节的无趣,决心 ...

  8. Python CGI编程

    CGI(Common Gateway Interface)通用网关接口,它是一段程序,运行在服务器上.如:HTTP服务器,提供同客户端HTML页面的接口. CGI程序可以是python脚本,PERL脚 ...

  9. python CGI编程Apache配置

    1. 编辑http.conf,添加两行,路径可以自定义 <Directory "C:/AppServ/www/cgi-bin"> AllowOverride None ...

随机推荐

  1. C#入门笔记1

    C#是用于创建要运行在.NET CLR上的应用程序的语言之一,从C和C++语言演化而来,是微软专门为使用.NET平台而创建的.优点:就是彻头彻尾为.NET Framework设计语言. C#能编写什么 ...

  2. Java虚拟机(JVM),JDK,JRE和JVM的区别——通过示例学习Java编程(2)

    Java虚拟机(JVM),JDK,JRE和JVM的区别 作者:CHAITANYA SINGH 来源:https://www.koofun.com/pro/kfpostsdetail?kfpostsid ...

  3. dp考试

    a[问题描述]

  4. (转)UVM挑战及概述

    UVM的调度也具有其独特的挑战,尤其是在调试的领域.其中的一些挑战如下: 1. Phase的管理:objections and synchronization 2. 线程调试 3. Tracing i ...

  5. Oracle汇总

    1.数据库事务并发会产生那些问题?有哪些隔离级别,分别能够避免什么错误,而无法避免什么错误? a.事务并发会导致三种问题:脏读.不可重复读.幻象读 脏读:读取了未提交的数据 不可重复读:前后读取同一行 ...

  6. Memcache笔记01-Memcache的安装

    memcached是什么? Memcached是一个高性能的分布式的内存对象缓存系统,目前全世界不少人使用这个缓存项目来构建自己大负载的网站,来分担数据库的压力,通过在内存里维护一个统一的巨大的has ...

  7. Android学习总结(十)———— Intent的使用

    一.Intent的基本概念 我们已经学习完了Android的四大组件了,在四大组件中我们用得最多的是Intent-Filter.Intent含义就是你想利用它调用哪个组件实现相关的功能,比如调用相机组 ...

  8. SQL增删查改语句

    一.增:有4种方法 1.使用insert插入单行数据: 语法:insert [into] <表名> [列名] values <列值> insert into sheet1 va ...

  9. (十四)maven之启动tomcat

    前言:在网上找了好几种方法启动web项目.比较好用的是:①在Project Facets勾上Dynamic....,但是这个方法会改变项目结构(把WebContent的东西都弄出来了):②使用jett ...

  10. 使用python批量建立文件

    for i in range(101,110): n = repr(i) + '.txt' file = open('c:\\ip\\' + n, 'w')