gpt4 book ai didi

Python 2/3 subprocess.Popen 和非 ascii 字符

转载 作者:太空宇宙 更新时间:2023-11-04 02:55:23 24 4
gpt4 key购买 nike

我正在尝试执行通过 subprocess.Popen 调用作为字符串传递的命令,我想知道如何以与大多数平台和 python 3/2 无关的方式执行此操作。这是一个例子:

# content of test.py
import subprocess

with open('test.cmd', 'rb') as f:
cmd = f.read().decode('UTF-8')

print(cmd)

pro = subprocess.Popen('bash',
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE)

out, err = pro.communicate(cmd)

pro.wait()
print(out)
print(err)

我正在通过从文件中读取来模拟具有非 ascii 字符的字符串的传递,这里是 test.cmd 文件的内容:

echo АБВГ

字符串读起来很好,print(cmd)语句的输出是正确的。然而,当我尝试通过 cmd 来传达功能时,它失败了。在 python 2 中,它表示“ascii”编解码器无法对字符进行编码,因此它似乎试图将其从 str 转换为 unicode,并且认为 str 只有 latin1 字符。我应该如何获得以正确方式编码的 str 对象?在 python 3 中,通信函数需要字节作为输入,但是应该使用什么编码?

最佳答案

In python 2 it says that 'ascii' codec can't encode characters, so it seems it tries to convert it to unicode

它尝试将 unicode 编码为 str。尝试显式编码 pro.communicate(cmd.encode('utf-8'))

关于Python 2/3 subprocess.Popen 和非 ascii 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42555153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com