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?
The Google Colaboratory (“Colab”) is a notebook (like a Jupyter Notebook) where you can run Python code in your Google Drive. You can write text, write code, run that code, and see the output – all in line in the same notebook.
Mounting DriveType a few letters like “m” in the search box to locate the mount command. Select Mount Drive command from the list. The following code would be inserted in your Code cell. Now, you are ready to use the contents of your drive in Colab.
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()
Please, try this function to Import a function from your drive to your colab notebook:
from google.colab import files
import zipfile, io, os
def upload_dir_file(case_f):
# author: yasser mustafa, 21 March 2018
# case_f = 0 for uploading one File or Package(.py) and case_f = 1 for uploading one Zipped Directory
uploaded = files.upload() # to upload a Full Directory, please Zip it first (use WinZip)
for fn in uploaded.keys():
name = fn #.encode('utf-8')
#print('\nfile after encode', name)
#name = io.BytesIO(uploaded[name])
if case_f == 0: # case of uploading 'One File only'
print('\n file name: ', name)
return name
else: # case of uploading a directory and its subdirectories and files
zfile = zipfile.ZipFile(name, 'r') # unzip the directory
zfile.extractall()
for d in zfile.namelist(): # d = directory
print('\n main directory name: ', d)
return d
print('Done!')
Then follow the following two steps: 1- If you have a file called (package_name.py), to upload it to your colab notebook call:
file_name = upload_dir_file(0)
2- Then, import your package:
import package_name
Note: you can use the same function to: 1- uploading file(csv, excel, pdf, ....):
file_name = upload_dir_file(0)
2- uploading Directory and its subdirectories and files:
dir_name = upload_dir_file(1)
Enjoy it!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With