Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何保存Python交互式会话?_Python_Shell_Read Eval Print Loop_Interactive Session - Fatal编程技术网

如何保存Python交互式会话?

如何保存Python交互式会话?,python,shell,read-eval-print-loop,interactive-session,Python,Shell,Read Eval Print Loop,Interactive Session,我发现自己经常使用Python的解释器来处理数据库、文件等——基本上是对半结构化数据进行大量手动格式化。我没有像我想的那样经常保存和清理有用的部分。有没有办法将我的输入保存到shell中(db连接、变量分配、小循环和逻辑位)——交互式会话的一些历史记录?如果我使用像script这样的东西,我会得到太多的标准噪声。我真的不需要对所有对象进行pickle处理——尽管如果有一个解决方案可以做到这一点,那也没关系。理想情况下,我只需要留下一个脚本,作为我交互创建的脚本运行,我可以删除不需要的部分。有没有

我发现自己经常使用Python的解释器来处理数据库、文件等——基本上是对半结构化数据进行大量手动格式化。我没有像我想的那样经常保存和清理有用的部分。有没有办法将我的输入保存到shell中(db连接、变量分配、小循环和逻辑位)——交互式会话的一些历史记录?如果我使用像
script
这样的东西,我会得到太多的标准噪声。我真的不需要对所有对象进行pickle处理——尽管如果有一个解决方案可以做到这一点,那也没关系。理想情况下,我只需要留下一个脚本,作为我交互创建的脚本运行,我可以删除不需要的部分。有没有一个软件包可以做到这一点,或者是一种DIY方法?

有一种方法可以做到这一点。将文件存储在
~/.pystartup

# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
#
# Store the file in ~/.pystartup, and set an environment variable to point
# to it:  "export PYTHONSTARTUP=/home/user/.pystartup" in bash.
#
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
# full path to your home directory.

import atexit
import os
import readline
import rlcompleter

historyPath = os.path.expanduser("~/.pyhistory")

def save_history(historyPath=historyPath):
    import readline
    readline.write_history_file(historyPath)

if os.path.exists(historyPath):
    readline.read_history_file(historyPath)

atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath
然后在shell中设置环境变量
PYTHONSTARTUP
(例如在
~/.bashrc
中):

export PYTHONSTARTUP=$HOME/.pystartup
您还可以添加此项以免费获取自动完成:

readline.parse_and_bind('tab: complete')
请注意,这仅适用于*nix系统。因为readline仅在Unix平台上可用。

如果您喜欢使用交互式会话,它非常有用。例如,对于您的用例,您只需输入
%save my_usivery_session 10-20 23
,即可将输入行10保存到20,将输入行23保存到
my_usivery_session.py
(为了帮助实现这一点,每行都以其编号作为前缀)

此外,文件规定:

此函数使用与输入范围相同的语法,然后将行保存到指定的文件名

例如,这允许引用较旧的会话,例如

%save current_session ~0/
%save previous_session ~1/

查看以快速了解这些功能。

此外,它还为Python会话提供了一个类似笔记本的界面。

除了IPython之外,类似的实用程序还具有“将输入的代码保存到文件”功能。


只是在碗里放另一个建议:

它有历史日志和变量资源管理器。如果您使用过MatLab,那么您将看到它们的相似之处

还有另一个选项--pyslice。 在“Wxpython2.8文档演示和工具”中,有一个名为“PyStices”的开源程序

您可以像编辑器一样使用它,它还支持像控制台一样使用它——像交互式解释器一样立即执行每一行

当然,所有代码块和每个代码块的结果都将自动记录到txt文件中

结果记录在相应代码块的后面。非常方便


我不得不努力寻找答案,我对iPython环境非常陌生

这会奏效的

如果您的iPython会话如下所示

In [1] : import numpy as np
....
In [135]: counter=collections.Counter(mapusercluster[3])
In [136]: counter
Out[136]: Counter({2: 700, 0: 351, 1: 233})
您希望保存从1到135的行,然后在同一ipython会话上使用此命令

In [137]: %save test.py 1-135
这将在当前目录(您启动ipython的地方)的test.py文件中保存所有python语句。

安装后,通过运行以下命令打开ipython会话:

ipython
在命令行中,只需运行以下Ipython“magic”命令即可自动记录整个Ipython会话:

%logstart
这将创建一个唯一命名的.py文件,并存储您的会话,以供以后用作交互式Ipython会话或在您选择的脚本中使用。

如果您正在使用,则可以使用带-f参数的magic函数将您以前的所有命令保存到文件中,p.e:

%history -f /tmp/history.py

有%history magic用于打印和保存输入历史(以及可选的输出)

要将当前会话存储到名为
my_history.py
的文件中,请执行以下操作:

>>> %hist -f my_history.py
History IPython存储您输入的命令及其生成的结果。您可以使用上下箭头键轻松浏览以前的命令,或者以更复杂的方式访问历史记录

您可以使用%history魔术函数检查过去的输入和输出。以前会话的输入历史记录保存在数据库中,可以将IPython配置为保存输出历史记录

其他几个魔术功能可以使用您的输入历史记录,包括%edit、%rerun、%recall、%macro、%save和%pastebin。可以使用标准格式引用行:

%pastebin 3 18-20 ~1/1-5
这将占用当前会话的第3行和第18至20行,以及上一会话的第1至5行

查看%history?对于Docstring和更多示例

另外,一定要探索IPython中用于变量轻量级持久化的功能

在IPython的数据库中存储变量、别名和宏


要在启动时自动恢复存储的变量,请在ipython_config.py中指定
c.StoreMagic.autorestore=True

就Linux而言,可以使用
script
命令记录整个会话。它是
util-linux
包的一部分,因此应该在大多数linux系统上使用。您可以创建和调用调用
script-cpython
的别名或函数,并将其保存到
typescript
文件中。例如,这里有一个这样的文件的重印

$ cat typescript                                                                                                      
Script started on Sat 14 May 2016 08:30:08 AM MDT
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'Hello Pythonic World'
Hello Pythonic World
>>> 

Script done on Sat 14 May 2016 08:30:42 AM MDT

这里的一个小缺点是,
脚本
会记录所有内容,甚至是换行,只要您点击backspaces等等。因此,您可能需要使用
来清理输出(请参阅)

一些评论询问如何一次保存所有IPython输入。对于IPython中的%save magic,您可以按如下所示以编程方式保存所有命令,以避免出现提示消息,并避免指定输入数字。 currentLine=len(In)-1 %保存-f my_会话1-$currentLine


-f
选项用于强制文件替换,
len(IN)-1
在IPython中显示当前输入提示,允许您以编程方式保存整个会话

适用于那些使用
spacemacs
ipython
的用户
d = {'a': 1, 'b': 2}
%store d  # stores the variable
del d

%store -r d  # Refresh the variable from IPython's database.
>>> d
{'a': 1, 'b': 2}
$ cat typescript                                                                                                      
Script started on Sat 14 May 2016 08:30:08 AM MDT
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'Hello Pythonic World'
Hello Pythonic World
>>> 

Script done on Sat 14 May 2016 08:30:42 AM MDT
len(all_suffixes)
';'.join(__PYTHON_EL_get_completions('''len'''))
';'.join(__PYTHON_EL_get_completions('''all_substa'''))
len(all_substantives_w_suffixes)
';'.join(__PYTHON_EL_get_completions('''len'''))
';'.join(__PYTHON_EL_get_completions('''all'''))
';'.join(__PYTHON_EL_get_completions('''all_'''))
';'.join(__PYTHON_EL_get_completions('''all_w'''))
';'.join(__PYTHON_EL_get_completions('''all_wo'''))
';'.join(__PYTHON_EL_get_completions('''all_wor'''))
';'.join(__PYTHON_EL_get_completions('''all_word'''))
';'.join(__PYTHON_EL_get_completions('''all_words'''))
len(all_words_w_logograms)
len(all_verbs)
$ cp ~/.pythonhist mycommands.py
>>> from mycommands import *
In [2]: %hist
In [3]: %%file my_file.py
   ...: # paste code here 
   ...:  
   ...:  
In [5]: !ls -l my_file.py
In [6]: !vi my_file.py
#gk-test.py or anything else would do
try: # use the try loop only if you haven't created the history file outside program
    username = open("history.txt").readline().strip("\n")
    user_age = open("history.txt").readlines()[1].strip("\n")
except FileNotFoundError:
    username = input("Enter Username: ")
    user_age = input("Enter User's Age: ")
    open("history.txt", "w").write(f"{username}\n{user_age}")
#Rest of the code is secret! try it your own!