关于linux输出重定向(1>/dev/null)的一个疑惑

发布于 2022-09-05 10:25:41 字数 1656 浏览 22 评论 0

一个Python脚本 展示结巴分词结果 如下所示

test.py
# -*- coding: utf-8 -*-
import jieba
print("/".join(jieba.cut("hello world")))
print("/".join(jieba.cut("你好世界")))

运行该脚本 一切正常

python test.py            
Building prefix dict from the default dictionary ...
Loading model from cache /var/folders/1k/p6dwx_0x28b6y752c1269hhw0000gn/T/jieba.cache
Loading model cost 0.398 seconds.
Prefix dict has been built succesfully.
hello/ /world
你好/世界

不想展示结巴相关的一些多余信息 于是通过Linux重定向的方式屏蔽这些信息 如下所示

python  test.py 2>/dev/null
hello/ /world
你好/世界

于是可以==》 如果将正常输出屏蔽掉的话(1>/dev/null) 应该只会显示 python test.py 1>/dev/null = python test.py - python test.py 2>/dev/null

Building prefix dict from the default dictionary ...
Loading model from cache /var/folders/1k/p6dwx_0x28b6y752c1269hhw0000gn/T/jieba.cache
Loading model cost 0.398 seconds.
Prefix dict has been built succesfully.

但是发现实际输出的更多

python  test.py 1>/dev/null
Building prefix dict from the default dictionary ...
Loading model from cache /var/folders/1k/p6dwx_0x28b6y752c1269hhw0000gn/T/jieba.cache
Loading model cost 0.379 seconds.
Prefix dict has been built succesfully.
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    print("/".join(jieba.cut("你好世界")))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

这多出来的输出是怎么来的啊?怎么一开始执行 python test.py的时候就没有这个输出呢?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

昔日梦未散 2022-09-12 10:25:41

你是 Python 2 么?Python 2 默认重定向到文件时是 ascii 编码的输出,在输出中文时会出错的。

解决方案是设置 PYTHONIOENCODING 为 utf-8,或者使用 Python 3。

不必在意 2022-09-12 10:25:41

兄弟报错了,报错了,报错了!

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

Python里面中文务必通过编码工具稍作处理:http://wklken.me/posts/2013/0...

深白境迁sunset 2022-09-12 10:25:41

楼上+1,都什么年代了,还在坚守python2?官方都弃疗了。python2在终端重定向以及管道处理上就是会各种问题,还有非ascii字符的处理简直蛋疼。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文