首页 > 解决方案 > python类型错误/打印到Popen错误

问题描述

好的,我喜欢 python subprocess.Popen 并发现了一件奇怪的事情:

OnlineListener = subprocess.Popen(("python", prog_dir + "online.py", prog_dir, port),
                                  shell=True,
                                  stdout=None,
                                  stdin=subprocess.PIPE)

print(b"f", file=OnlineListener.stdin, flush=True)

但我得到了奇怪的错误:

Traceback (most recent call last):
  File "C:/##########/PycharmProjects/#####/main.py", line 53, in <module>
    processes = run_proc()
  File "C:/##########/PycharmProjects/#####/main.py", line 27, in run_proc
    print(b"f", file=OnlineListener.stdin, flush=True)
TypeError: a bytes-like object is required, not 'str'

需要类似字节的对象,而不是“str”

我认为错误是由于b"f",但实际上:

print(type(b'f')) # return: <class 'bytes'>

有人可以帮我弄这个吗?
UPD。 也许我真的不需要这个问题的答案,但看看这个:

    scoper.stdin.write("end\n".encode())
TypeError: write() argument must be str, not bytes
#################但是########################。
    scoper.stdin.write("end\n")
TypeError: a bytes-like object is required, not 'str'

标签: pythonsubprocess

解决方案


print函数始终将给定的类文件对象视为文本流,调用printwithb'f'将简单地输出"b'f'"为文本。但是Popen.stdin除非给出一个参数,否则它将是一个字节流encoding,而你没有给出,所以打印任何东西都会导致上述错误。

要解决此问题,您可以encoding在初始化时使用参数Popen

OnlineListener = subprocess.Popen("python",
                                  shell=True,
                                  stdout=None,
                                  stdin=subprocess.PIPE,
                                  encoding='utf-8')

或使用该write方法代替print

OnlineListener.stdin.write(b'f\n')

推荐阅读