python - python 类型错误/打印到 Popen 错误

标签 python subprocess

好吧,我很喜欢 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'

bytes-like object is required, not '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'

最佳答案

print函数始终将给定的类文件对象视为文本流,并且使用 b'f' 调用 print 将简单地输出 "b'f'" 作为文本。但是Popen.stdin除非给出了 encoding 参数,否则将是一个字节流,而您没有给出,因此向其中打印任何内容都会导致上述错误。

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

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

或者使用write方法代替print:

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

关于python - python 类型错误/打印到 Popen 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59636129/

相关文章:

python:子进程调用运行后台进程挂起的脚本

python - 使用子进程调用时,ssh-keygen 会引发密码太短错误

python - 使用子进程发送键盘事件

python-3.x - 如何修复 subprocess.check_output() 中的挂起

python - 如果数字为 0 或大于 1,则将 's' 添加到字符串

python - 无法使用 Subprocess 模块成功解析并运行长命令

python - 如何在具有共享模型和数据库的同一项目中拆分 Django 应用程序的部署?

python - 如何访问 NoneType 类型?

Python isinstance() 的 float 失败断言测试

python : Extending Exception class