Tuppitappi
Tuppitappi

Reputation: 149

How to save python notebook cell code to file in Colab

TLDR: How can I make a notebook cell save its own python code to a file so that I can reference it later?

I'm doing tons of small experiments where I make adjustments to Python code to change its behaviour, and then run various algorithms to produce results for my research. I want to save the cell code (the actual python code, not the output) into a new uniquely named file every time I run it so that I can easily keep track of which experiments I have already conducted. I found lots of answers on saving the output of a cell, but this is not what I need. Any ideas how to make a notebook cell save its own code to a file in Google Colab?

For example, I'm looking to save a file that contains the entire below snippet in text:

df['signal adjusted'] = df['signal'].pct_change() + df['baseline']
results = run_experiment(df)

Upvotes: 2

Views: 1548

Answers (2)

korakot
korakot

Reputation: 40858

All cell codes are stored in a List variable In.

For example you can print the lastest cell by

print(In[-1])  # show itself
# print(In[-1])  # show itself

So you can easily save the content of In[-1] or In[-2] to wherever you want.

Upvotes: 4

Tuppitappi
Tuppitappi

Reputation: 149

Posting one potential solution but still looking for a better and cleaner option.

By defining the entire cell as a string, I can execute it and save to file with a separate command:

cell_str = '''
df['signal adjusted'] = df['signal'].pct_change() + df['baseline']
results = run_experiment(df)
'''
exec(cell_str)
with open('cell.txt', 'w') as f:
    f.write(cell_str)

Upvotes: 0

Related Questions