gpt4 book ai didi

python - Bash - 标准输出文本在重定向到文件时被截断

转载 作者:太空狗 更新时间:2023-10-29 11:22:21 26 4
gpt4 key购买 nike

在 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()

当以交互方式输入时,代码工作正常 - 没有截断发生。一旦我将该代码放入脚本并运行它,一些长行就会被截断。为什么会这样?

最佳答案

您可以在 bash 中执行命令之前尝试使用 COLUMNS 变量;

感受不同:

列=80 dpkg -l和列=300 dpkg -l <​​/p>

关于python - Bash - 标准输出文本在重定向到文件时被截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20375357/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com