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