Python 子进程/Popen 标准输出被截断

标签 python pipe subprocess popen

Popen stdout 的输出与从 Shell 运行命令或使用 os.system 不同:

cmd = ['git', 'diff', commitHash, '--stat']

print Popen(cmd, stdout=PIPE).stdout.read().strip()
os.system(' '.join(cmd))

Popen 的输出:

 src/tech/dalvik/sidebar.md                         |   10 -
 .../encryption/android_crypto_implementation.md    |  359 --
 src/tech/encryption/index.md                       |   22 -
 src/tech/encryption/sidebar.md                     |    9 -
 src/tech/index.md                                  |   58 -
 src/tech/nfc/index.md                              |   25 -
 src/tech/nfc/sidebar.md                            |    7 -
 src/tech/sidebar.md                                |    5 -
 templates/footer                                   |    3 +-
 templates/includes                                 |    2 +-
 templates/sidebar                                  |    2 +-
 257 files changed, 32311 insertions(+), 11358 deletions(-)

来自 os.system 的输出(与从 Shell 运行相同)

 src/tech/dalvik/sidebar.md                                         |   10 -
 src/tech/encryption/android_crypto_implementation.md               |  359 ---------
 src/tech/encryption/index.md                                       |   22 -
 src/tech/encryption/sidebar.md                                     |    9 -
 src/tech/index.md                                                  |   58 --
 src/tech/nfc/index.md                                              |   25 -
 src/tech/nfc/sidebar.md                                            |    7 -
 src/tech/sidebar.md                                                |    5 -
 templates/footer                                                   |    3 +-
 templates/includes                                                 |    2 +-
 templates/sidebar                                                  |    2 +-
 257 files changed, 32311 insertions(+), 11358 deletions(-)

如何让 subprocess.Popenos.system 一样工作?

我在这里发现了类似的问题:Stdout captured from pipe in Python is truncated ,但设置 LANG 环境变量似乎不起作用。

谢谢!

最佳答案

我认为输出实际上并没有被截断。

可能 git 正在为您提供不同的输出,试图最好地向您呈现差异统计信息。

根据您的示例,我猜问题是环境变量 COLUMNS 的值不同。

检查您的终端有多少列:

$ echo $COLUMNS

并在 Popen 调用中设置此环境变量:

Popen(cmd, stdout=PIPE, env={'COLUMNS':'249'})

关于Python 子进程/Popen 标准输出被截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27328428/

相关文章:

使用命名空间的 Python ElementTree find()

用于在长列表中查找唯一名称的 Python 命令

Python子进程没有正确执行程序

python 子进程.Popen

java - 使用父进程类路径启动Java子进程

python - 根据 block 权重拆分数组

python - Python Pandas 中的 Groupby/Sum - 零计数不显示......有时

c - 通过 argv 传递管道地址

c - 在**可移植 C** 中,如何启动将命令的标准输入连接到启动程序的标准输出的命令?

android - 应用程序在 pclose 上崩溃