From a Colab notebook, I would like to call a python function that I wrote in a separate python file. How do I do that?
Edit: If you would like to import a local module, you'll want to edit your sys.path
to point to that new directory. Here's an example notebook:
https://colab.research.google.com/notebook#fileId=1PtYW0hZit-B9y4PL978kV2ppJJPhjQua
Original reply: Sure, here's an example notebook: https://colab.research.google.com/notebook#fileId=1KBrq8aAiy8vYIIUiTb5UHG9GKOdEMF3n
There are two cells: the first defines a .py
file with a function to be imported.
%%writefile example.py
def f():
print 'This is a function defined in a Python source file.'
The second cell uses execfile
to evaluate that .py
file in the notebook's Python interpreter.
# Bring the file into the local Python environment.
execfile('example.py')
# Call the function defined in the file.
f()