2016-08-19 76 views
4

我想捕獲Python shell輸出以及發送給它的輸入。例如,在下面的使用情況下,幫助()也應存在於capture.log的第4行:捕獲交互式Python shell輸出以及輸入

$ 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/. 
.... 
.... 

回答

5

假設類似Unix的環境中,可以捕獲所有tty輸入和輸出與所述script命令:

$ 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/. 
.... 
.... 

正如您所看到的,輸入和輸出都被捕獲,但它們沒有對齊。