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. Ionic之$scope 依赖注入报错

    在开发Ionic过程中,发现会报在 LoginController 中引用locals报错,具体报错问题: ionic.bundle.js:19526 Error: [$injector:unpr] ...

  2. hybrid app开发中:苹果移动设备实用Meta标签

    hybrid app开发中:苹果移动设备实用Meta标签 “apple-mobile-web-app-status-bar-style”作用是控制状态栏显示样式 具体效果如下: status-bar- ...

  3. uvm_scoreboard——得分

    scoreboard 是验证平台很重要的一部分,因为,验证就是给激励,然后,检查结果.而scoreboard 就是肩负这检查结果的重任.测试用例能不能过,全由scoreboard说了算. A scor ...

  4. (七)mybatis之创建SqlSession

    前文提到了SqlSessionFactory接口,可以用来生产SqlSession.而SqlSession其实也是一个接口类,也就是起到一个门面的角色.那么谁是真正干活的呢?------Executo ...

  5. (十二)maven之nexus仓库的基本用法

    nexus仓库的基本用法 ① 启动nexus. 上一章有提到:https://www.cnblogs.com/NYfor2018/p/9079068.html ② 访问http://localhost ...

  6. JSON数组不用字符串转换的写法

    var organization = []; //机构组织 //初始化用户数据列表中用户机构列的数据源 admin.ajax("GetOrganizationInfo", null ...

  7. (转)SpringMVC学习(三)——SpringMVC的配置文件

    http://blog.csdn.net/yerenyuan_pku/article/details/72231527 读者阅读过SpringMVC学习(一)——SpringMVC介绍与入门这篇文章后 ...

  8. CF 1119F Niyaz and Small Degrees

    打VP的时候由于CXR和XRY切题太快了导致我只能去写后面的题了 然而VP的时候大概还有一小时时想出了\(O(n^2\log n)\)的暴力,然后过了二十分钟才想到删点的优化 结果细节很多当然是写不出 ...

  9. 在idea下创建maven

    之前一直用eclipse,现在要用idea写一个安装过程玩玩 一:New Project 二:选择maven,在project SDK上选择你安装的jdk,默认安装在c:/Program Files ...

  10. Robot Framework(十一) 执行测试用例——后处理输出

    3.3后处理输出 在测试执行期间生成的XML输出文件可以在之后由rebot工具进行后处理,该工具是Robot Framework的组成部分.在测试执行期间生成测试报告和日志时会自动使用它,但在执行后也 ...