如何通过 Popen.communicate() 传递 unicode 文本消息? [英] How to pass unicode text message through Popen.communicate()?

查看:38
本文介绍了如何通过 Popen.communicate() 传递 unicode 文本消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 python 脚本,它在执行时向终端显示 Unicode 消息.所以我想在进程运行时在网页中显示该消息.我能够通过 Popen 包运行脚本,但其接收脚本输出的communication() 方法无法接收Unicode 文本.

I have python script which display Unicode message to the terminal while executing. So i want to display that message in the web page while the process runs. I was able to run the script through Popen package but its communicate() method which receives the output of the scripts can't receive Unicode text.

UnicodeEncodeError: \'charmap\' codec can\'t encode characters in position 12-15: character maps to <undefined>\r\n'

所以我尝试将消息作为可以通过它的字节传递,但我无法稍后对其进行解码以讨论此问题,请转到:如何解码字节对象的字符串表示?

So i try to pass the message as bytes which can pass through it but i can't decode it later to discuss about this question go to: How to decode a string representation of a bytes object?

但是现在在这篇文章中我想知道通过 Popen.communicate() 传递 Unicode 文本的方法我这里的代码是

But Now in this post i want to know the way to pass Unicode text through Popen.communicate() My code here is

from subprocess import Popen, PIPE
scripts = os.path.join(os.getcwd(), 'scripts')
p = Popen(["python", "tasks.py"],bufsize=0, cwd=scripts, stdout=PIPE, stderr=PIPE)
out,err = p.communicate()

推荐答案

@snakecharmerb 的评论就是解决方案.

The comment of @snakecharmerb is the solution.

您必须在启动子 Python 进程之前设置 PYTHONIOENCODING 变量,以允许它以 UTF-8 正确编码其输出.然后你只需解码你在父级中得到的内容:

You must set the PYTHONIOENCODING variable before launching the child Python process to allow it to correctly encode its output in UTF-8. Then you have just to decode what you get in the parent:

from subprocess import Popen, PIPE
import os

os.environ['PYTHONIOENCODING'] = 'UTF-8'
scripts = os.path.join(os.getcwd(), 'scripts')
p = Popen(["python", "tasks.py"],bufsize=0, cwd=scripts, stdout=PIPE, stderr=PIPE)
out,err = p.communicate()
print(out.decode())

如果你有Python>=3.6,你可以直接跳出来报错为unicode字符串:

If you have Python>=3.6, you can directly get out and err as unicode strings:

os.environ['PYTHONIOENCODING'] = 'UTF-8'
scripts = os.path.join(os.getcwd(), 'scripts')
p = Popen(["python", "tasks.py"],bufsize=0, cwd=scripts, stdout=PIPE, stderr=PIPE, encoding='UTF-8')
out,err = p.communicate()
print(out)

这篇关于如何通过 Popen.communicate() 传递 unicode 文本消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆