如何在主进程配置Python子进程的标准流为UTF-8编码?
如何从主进程配置子进程的标准流使用UTF-8编码
以下是用于测试sys.stdout编码规则的SSCCE,它通过创建临时Python文件并调用subprocess模块运行:
subp_code = "import sys print(sys.stdout.encoding)" test_fname = 'sub_test123123123_TMP.py' # 估计没人会有重名的重要文件 with open(test_fname, 'w') as f: f.write(subp_code) import os, sys, subprocess pr = subprocess.Popen(['python', test_fname], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = pr.communicate() # 一次性交互用这个,不要用在需要来回通信的进程上 os.remove(test_fname) # 删除临时文件 print('当前进程编码:', sys.stdout.encoding) #utf-8 print('子进程编码:', out.decode().strip()) #Windows下为cp1252
在Windows系统中,子进程的标准输出编码是cp1252而非UTF-8,这会导致原本在UTF-8环境下正常的Unicode打印语句报错:
print(chr(1234)) #UnicodeEncodeError: 'charmap' codec can't encode character '\u04d2' in position 0: character maps to <undefined>
在Popen参数中添加encoding='utf-8'无效:这只会让主进程和子进程以字符串形式通信,但子进程自身的标准流编码还是cp1252。
虽然可以在子进程内手动修改编码:
sys.stdout.reconfigure(encoding='utf-8')
但我不想在所有子进程里都加这行代码,请问有没有办法直接从主进程配置子进程的标准流使用UTF-8编码?
内容的提问来源于stack exchange,提问作者Kevin Kostlan
相关产品推荐
相关产品推荐

