python - 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'
解决方案
该print
函数始终将给定的类文件对象视为文本流,调用print
withb'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')
推荐阅读
- database - 为什么表中的数据不显示?
- c# - 如何在不删除文本值的情况下“禁用”单选按钮,以及是否选中它
- android-studio - 移动文件夹后,Flutter 项目将无法在 Android Studio 上运行
- vba - 如何加快 MS Word 文档中多个单词的 VBA 样式替换?
- sql-server - 根据月份使变量足够动态地改变值
- excel - 尝试做计算乘法的 sumifs 公式
- r - 在 R 中排列 4 个 plotly 饼图
- qt - 如何在 QML 5.14 中使用 Markdown 格式
- html - 将响应按钮放置在 TextArea 内
- javascript - ReactJS:如何传递字符串以用作函数名?