过去一周我一直在编辑Jupyter笔记本,并尝试今天保存它。在尝试保存时,我收到了错误,因此我刷新了页面并成功保存了它。
然而,令我沮丧的是,几乎所有的命令历史都丢失了!我仍然可以访问变量(内核永远不会死),但我无法访问任何代码。
有没有办法恢复代码?内核仍在运行,但我的笔记本中没有看到任何检查点。
答案 0 :(得分:8)
您可以获取IPython历史记录,Jupyter Notebook将其用作其内核。在其中一个单元格中运行:
%history
这将转储您在当前IPython会话中运行的每个命令的历史记录(好的,坏的和丑的)。它可能比你想要的更多,但它比失去你所有的工作更好。
答案 1 :(得分:6)
类似的事情发生在我身上,我无法保存所做的工作,刷新页面并丢失了所有命令。
您可以获取整个笔记本的历史记录,并通过运行将输出重定向到任何给定文件
#Import the necessary libraries
import pandas as pd
from pulp import *
#Import the necessary liberaries
import pandas as pd
from pulp import *
#Create LpProblem
prob = LpProblem("Simple Diet Problem",LpMinimize)
#Read the file
df = pd.read_csv("The Diet Problem.csv")
#Creat a list of food items
food_items = list(df['Foods'])
#Create a dictionary of cost for all foods
cost = dict(zip(food_items,df['price']))
#Create a dictionary of A for all foods
A = dict(zip(food_items,df['A']))
#Create a dictionary of C for all foods
C = dict(zip(food_items,df['C']))
#Create a dictionary of B1 for all foods
B1 = dict(zip(food_items,df['B1']))
#Create a dictionary of B2 for all foods
B2 = dict(zip(food_items,df['B2']))
I
#Create food variable with a lower bound = 0
food_vars = LpVariable.dicts("Food",food_items,lowBound=0, cat='Integer')
#Building the LpProblem by adding the main objective function
prob += lpSum([cost[i]*food_vars[i] for i in food_items])
=
#Add the constraints to the model
prob += lpSum([A[f] * food_vars[f] for f in food_items]) == 700
prob += lpSum([C[f] * food_vars[f] for f in food_items]) ==700
prob += lpSum([B1[f] * food_vars[f] for f in food_items]) == 700
prob += lpSum([B2[f] * food_vars[f] for f in food_items]) ==700
#Solve the problem and display the status
prob.solve()
print ("Status:", LpStatus[prob.status])
Status: Infeasible
#Display the full solution
for v in prob.variables():
if v.varValue>=0:
print(v.name, "=", v.varValue)
Food_Beef = 0.0
Food_CHK = 19.543147
Food_FISH = 0.0
Food_HAM = 0.0
Food_MCH = 16.345178
Food_MTL = 4.2639594
Food_SPG = 0.0
Food_TUR = 0.0
就我而言,我将其重定向到(.py)文件。您可以在https://ipython.readthedocs.io/en/stable/interactive/magics.html下的“%history”下找到更多文档。
答案 2 :(得分:0)
如果您的内核没有重新启动,您可以从 _i{1,2,3,...}
等全局变量中获取您的代码。
找到代码的最简单方法是运行类似
print([k for k, v in globals.items() if 'some unique code snippet' in str(v)])
假设你有类似 ['_i2', '_i5', '_i9']
的东西,那么你可以
print(_i9)
并将其复制粘贴到新单元格中。