Python3 Popen:我每次都必须使用 .encode() 吗?

Python3 Popen: Do I have to use .encode() every time?

我有一个程序用于测试另一个程序。它像这样使用 Popen:

testProgram = subprocess.Popen(args, stdin = subprocess.PIPE, stdout = subprocess.PIPE)

在 python2 中,我向 testProgram 发送指令,如下所示:

testProgram.stdin.write("count "+vals[0]+"\n")

在 python3 中,write 需要一个类似字节的对象而不是 str。我认为这要求我在每次写入时都使用 testProgram.stdin.write(("count "+vals[0]+"\n").encode("utf-8")) 之类的东西,但我显然不会那样做。

有没有一种简单的方法可以让 Popen 的标准输入在 python3 中作为文本流工作,还是我应该坚持 python2? 参数 universal_newlines = True looks like it should work,但对我来说,程序只是冻结在 result = testProgram.stdout.readline()

使用 universal_newlines=True 是正确的解决方案,但在 python3 中,输入不会自动刷新每个换行符,除非您将 bufsize=1 传递给 Popen。

为了让程序在 python3 中运行,Popen 行变为:

testProgram = subprocess.Popen(args, stdin = subprocess.PIPE, stdout = subprocess.PIPE, universal_newlines = True, bufsize = 1)