Bash - 当将stdout文本重定向到文件时,文本会被截断

3
在 Linux(Ubuntu 12.04 LTS)上使用 Bash 工作时,有时文本输出会被截断。我将解释一下我的意思。
假设你发出 "dpkg -l" 命令。dpkg 然后将已安装软件包的长列表写入其标准输出,文本行不会被截断,一切正常。现在,你尝试将命令的输出转储到文件中——"dpkg -l > dump"。当查看文件内容时,你会发现部分行(那些相当长的行)已被截断。是什么逻辑导致了这种行为?
此外,我进行了一个小实验。在与 Python 解释器交互地工作时,我输入以下内容:
from os import popen2

child_input, child_output = popen2("dpkg -l", "t")          # running the command "dpkg -l" in a subprocess so that I can then obtain what it writes to its stdout via a pipe

dump_file = open("dump", 'w')                               # create a file to write to

for string in child_output:                                 
    dump_file.write(string)                                 # writing the child's output to the dump file, one line at a time

dump_file.close()

当代码以交互方式输入时,代码能够正常工作 - 没有截断发生。但是一旦我把这段代码放到脚本中并运行它,部分长行就被截断了。为什么会出现这种情况?

5
我猜是因为dpkg -l基本上是dpkg-query,它会根据环境变量COLUMNS生成输出结果... 只是在正常运行时,如果使用一个调整大小的终端窗口,输出结果会被截断... - Jon Clements
您可以使用subprocess模块将子进程的输出转储到文件中:subprocess.check_call("dpkg -l".split(), stdout=open("dump","wb")) - jfs
1个回答

0

在Bash执行命令之前,可以尝试使用COLUMNS变量;

感受一下不同:

COLUMNS=80 dpkg -l 和 COLUMNS=300 dpkg -l


感谢stimur和所有抽出时间回答问题的人。这种行为确实受COLUMNS变量的影响。顺便说一下,关于这个问题有一个类似的主题。http://stackoverflow.com/questions/7648718/redirection-operator-is-limiting-columns在开始这个问题之前我应该先四处看看。 - Jared Nash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接