I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like script I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach?
当前回答
我想建议另一种在linux上通过tmux维护python会话的方法。运行tmux,将自己附加到所打开的会话(如果直接打开后没有附加)。执行python并在它上做任何事情。然后从会话中分离。从tmux会话分离并不会关闭会话。会议仍然开放。
这种方法的优点: 您可以从任何其他设备连接到此会话(如果您可以SSH您的pc)
这种方法的缺点: 在python解释器真正存在之前,此方法不会放弃被打开的python会话所使用的资源。
其他回答
还有另一种选择——耻骨瓣切除术。 在“wxpython 2.8文档演示和工具”中,有一个名为“pyslices”的开源程序。
你可以像编辑器一样使用它,它也支持像控制台一样使用----,像交互式解释器一样执行每一行,具有即时回显。
当然,所有的代码块和每个块的结果都会自动记录到一个TXT文件中。
结果被记录在相应代码块的后面。非常方便。
对于那些使用spacemacs和python层附带的ipython的人来说,save magic会创建大量不必要的输出,因为不断的自动补全命令在后台工作,例如:
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)
为了避免这种情况,只需保存ipython缓冲区,就像通常保存任何其他:spc f一样
如果使用bpython,所有的命令历史都会默认保存到~/.pythonhist。
要保存命令以供以后重用,您可以将它们复制到python脚本文件中:
$ cp ~/.pythonhist mycommands.py
然后编辑该文件以清理它并将其放在Python路径下(全局或虚拟环境的site-packages,当前目录,在*.pth中提到,或其他方式)。
要将命令包含到你的shell中,只需从保存的文件中导入它们:
>>> from mycommands import *
除了IPython之外,类似的实用程序bpython还有一个“将您输入的代码保存到文件中”的特性
我想建议另一种在linux上通过tmux维护python会话的方法。运行tmux,将自己附加到所打开的会话(如果直接打开后没有附加)。执行python并在它上做任何事情。然后从会话中分离。从tmux会话分离并不会关闭会话。会议仍然开放。
这种方法的优点: 您可以从任何其他设备连接到此会话(如果您可以SSH您的pc)
这种方法的缺点: 在python解释器真正存在之前,此方法不会放弃被打开的python会话所使用的资源。