简体   繁体   English

捕获交互式Python shell输出以及输入

[英]Capture interactive Python shell output along with input

I want to capture the Python shell output along with the input sent to it. 我想捕获Python shell输出以及发送给它的输入。 For example, in the following use case, help() should also be present in Line 4 of capture.log: 例如,在以下用例中,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/.
....
....

Assuming a Unix-like environment, you can capture all tty input and output with the script command: 假设类似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

If, as in the question example, Python is driven completely by stdin pipe and the goal is to capture the pipe input and Python output, you can get close by using the tee command: 如果在问题示例中,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/.
....
....

As you can see, the input and output are both captured, but they're not aligned. 如您所见,输入和输出都被捕获,但它们没有对齐。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM