Python标准输入受TERM设置的影响

时间:2014-06-26 04:03:37

标签: python bash terminal term

对于一个小项目,我决定第一次给Python。 我让我的代码工作正常,但在处理python脚本的输出时,我注意到了一些奇怪的行为。

似乎所使用的终端设置会影响python的打印功能输出。

以下是我的代码的简化版本:

#!/usr/bin/python
print 'one two'

正常输出正如您所期望的那样:

~/$test.py
one two
~/$

但是如果你尝试让bash读取输出,它就会失败。 以下是我如何复制问题:

~/$ set -x
~/$ ./test.py | while read V1 V2; do echo $V1; echo $V2; grep -c "$V1" /myfile; done
+ ./test.py
+ read V1 V2
+ echo 'one'
one
+ echo two
two
+ grep -c 'one' /etc/passwd
grep: Unmatched [ or [^
+ read V1 V2
~/$ set +x

注意'one'周围的单引号? grep抱怨的'[''在哪里? 当我将输出重定向到文件,并将其加载到vi中时,我在输出前面看到了一些控制字符。

要解决此问题,请按以下方式运行命令:

~/$ (TERM=dumb; ./test.py | while read V1 V2; do echo $V1; echo $V2; grep -c "$V1" /myfile; done)

这很好用,但我真的很想知道为什么python决定它需要格式化终端的输出。更重要的是,我该如何控制这种行为?

感谢您的时间。

0 个答案:

没有答案
相关问题