捕获交互式Python Shell的输出和输入

5
我希望能够捕获Python shell的输出以及发送给它的输入。例如,在以下用例中,help() 应该出现在 capture.log 的第四行:
$ 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/.
....
....
1个回答

5
假设您使用的是类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/.
....
....

正如您所看到的,输入和输出都被捕获了,但它们并不对齐。


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