python类型出错/打印到Popen错误
好的,我很喜欢python subprocess.Popen,发现了一件奇怪的事情:python类型出错/打印到Popen错误,python,subprocess,Python,Subprocess,好的,我很喜欢python subprocess.Popen,发现了一件奇怪的事情: OnlineListener = subprocess.Popen(("python", prog_dir + "online.py", prog_dir, port), shell=True, stdout=None,
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'
有人能帮我吗?UPD. 也许我真的不需要这个问题的答案,但看看这个:
scoper.stdin.write("end\n".encode())
TypeError: write() argument must be str, not bytes
##################但是。
该函数始终将给定的类似文件的对象视为文本流,使用b'f'
调用print
只需将“b'f'
作为文本输出即可。但是,除非给出了编码
参数,否则它将是一个字节流,而您没有这样做,因此向它打印任何内容都会导致上述错误
要解决此问题,可以在初始化Popen
时使用encoding
参数:
OnlineListener = subprocess.Popen("python",
shell=True,
stdout=None,
stdin=subprocess.PIPE,
encoding='utf-8')
或者使用write
方法而不是print
:
OnlineListener.stdin.write(b'f\n')
你的代码打算做什么?此外,变量和函数名应遵循带有下划线的
小写形式。如果使用元组作为第一个参数,则可能需要shell=False
。关于更新后的问题,我的答案建议只使用两种解决方案中的一种,而不是两种。使用encoding
初始化Popen
会使stdin
属性成为文本流,使用bytes
对象调用write
会引发TypeError:write()参数必须是str,而不是bytes
error。如果该程序的输入是全部文本,我建议您只需使用编码初始化Popen
,并使用打印
进行输出。
OnlineListener = subprocess.Popen("python",
shell=True,
stdout=None,
stdin=subprocess.PIPE,
encoding='utf-8')
OnlineListener.stdin.write(b'f\n')