我有一个 Python 脚本:
x=1.
x
Run Code Online (Sandbox Code Playgroud)
我想从命令行生成以下文本:
Python 3.7.4 (default, Aug 13 2019, 20:35:49)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x=1.
>>> x
1.0
Run Code Online (Sandbox Code Playgroud)
并将其保存到文件中。
这是我通过交互式复制和粘贴代码到 Python 解释器中可以获得的内容。
我考虑了以下消息:
我考虑过
任何帮助将不胜感激。
如果您使用的是 IPython,您可以使用%history魔术命令将您的历史记录(包括输入和输出)导出到一个文件中。
%history -o -p -f session.txt
Run Code Online (Sandbox Code Playgroud)
该-o标志加输出,-p标志显示了传统的Python提示和-f标志出口到一个文件中。
我最新会话的 session.txt 文件如下所示:
>>> import pandas as pd
>>> df = pd.read_clipboard()
>>> df
time a b
0 0.000 6 5
1 0.008 6 9
2 0.016 1 9
3 0.024 2 7
4 0.032 1 5
>>> x = [-6, -4, -3, -2, -1, 0.5, 1, 2, 4, 6]
>>> df['a_'] = df.a.apply(lambda r: x[r-1])
>>> %history?
>>> %history -o -p -f session.txt
Run Code Online (Sandbox Code Playgroud)
值得注意的是,只显示了输出。print声明中的文本不会出现。
假设这是通过标准 GNU/Linux 终端环境运行的,可以考虑使用该script命令制作终端会话的打字稿。这对各种应用程序都很有用,而不是专门用于记录 python 会话。基本上,在这种情况下如何使用它的顺序如下:
$ script
$ python
>>> python commands
>>> exit()
CTRL-D
cat typescript
Run Code Online (Sandbox Code Playgroud)
输出将在工作目录中的打字稿文件中创建。它不是纯文本文件,但如果您只是希望记录该python部分,则它非常接近。