python - 捕获交互式 Python shell 输出和输入

标签 python bash shell stdout stdin

我想捕获 Python shell 输出以及发送给它的输入。例如,在以下用例中,help() 也应出现在 capture.log 的第 4 行中:

$ echo "help()" | python3 -i > capture.log   2>&1
$ cat capture.log
Python 3.4.2 (default, Oct  8 2014, 10:45:20) 
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
Welcome to Python 3.4's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.4/tutorial/.
....
....

最佳答案

假设一个类 Unix 环境,您可以使用 script 命令捕获所有 tty 输入和输出:

$ script capture.log
Script started, output file is capture.log
$ python3
# python interactive session here
$ exit
Script done, output file is capture.log
$ cat capture.log
Script started on Thu Aug 18 21:21:55 2016
$ python3
Python 3.5.2 (default, Jul 21 2016, 07:25:19) 
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> help()

Welcome to Python 3.5's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.5/tutorial/.

....
....
>>> ^D
$ exit

Script done on Thu Aug 18 21:22:06 2016

如果像问题示例中那样,Python 完全由 stdin 管道驱动并且目标是捕获管道输入和 Python 输出,您可以使用 tee命令:

$ echo "help()" | tee capture.log | python3 -i >> capture.log 2>&1
$ cat capture.log 
help()
Python 3.5.2 (default, Jul 21 2016, 07:25:19) 
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 
Welcome to Python 3.5's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.5/tutorial/.
....
....

如您所见,输入和输出都被捕获,但它们没有对齐。

关于python - 捕获交互式 Python shell 输出和输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39030061/

相关文章:

python - Elasticsearch 滚动结束不返回任何内容

python - 从 JSON 中过滤空值

regex - 删除重复的文件扩展名

linux - 如何使用 Linux 命令找到我的 shell 版本?

shell - 如何在 Unix 中同时搜索并执行两个脚本?

python - CNTK 和 UserMinibatchSource 预取

python - BeautifulSoup getText 从 <p> 之间,不拾取后续段落

当我用 bash 运行程序时,C fopen 不起作用

linux - 如何快速推断仅显示开始时间的文件的开始/结束时间?

linux - 我如何在 Windows 上运行 Ubuntu 的/bin/bash