Skip to main content
 首页 » 编程设计

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

2024年10月01日8leader

我正在尝试执行通过 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'))