我正在尝试执行通过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中,communication函数期望字节作为输入,但是应该使用哪种编码?

最佳答案

在python 2中,它说“ ascii”编解码器无法编码字符,因此似乎试图将其转换为unicode


它尝试将unicode编码为str。尝试对其进行明确编码pro.communicate(cmd.encode('utf-8'))

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

10-12 16:34
查看更多