proc.communicate() 输出在 Django Python 中不换行

1 投票
1 回答
843 浏览
提问于 2025-04-16 03:26

我有一个子进程,使用 communicate 来获取输出,并把它保存到我的数据库里:

  p = Popen([str(pre_sync), '-avu', str(src), str(dest)], stdout=PIPE)
  syncoutput = p.communicate()
  check.log = syncoutput

这一切都运行得很好,但从 communicate 得到的输出看起来是这样的:

('sending incremental file list\n\nsent 89 bytes  received 13 bytes  204.00 bytes/sec\ntotal size is 25  speedup is 0.25\n', None)

所有内容都在一行里,并且里面有 "\n" 这个符号。有没有办法让我每一行都能单独换行显示呢?提前谢谢你。

1 个回答

4
syncoutput,sync_error = p.communicate()
print(syncoutput)

p.communicate() 这个方法会返回一个包含两个部分的元组,分别是标准输出(stdout)和标准错误(stderr)的内容。当你打印这个元组时,会看到里面有 \n 这样的字符。可是当你打印新的 syncoutput 字符串时,得到的就是格式化后的文本。

撰写回答