Colabノートブックから、別のpythonファイルに記述したpython関数を呼び出します。どうすればよいですか?
Edit:ローカルモジュールをインポートする場合は、sys.path
を編集してその新しいディレクトリを指すようにします。以下にノートブックの例を示します: https://colab.research.google.com/notebook#fileId=1PtYW0hZit-B9y4PL978kV2ppJJPhjQua
元の返信:もちろん、ここにノートブックの例があります: https://colab.research.google.com/notebook#fileId=1KBrq8aAiy8vYIIUiTb5UHG9GKOdEMF3n
2つのセルがあります。最初のセルは、インポートする関数を含む.py
ファイルを定義します。
%%writefile example.py
def f():
print 'This is a function defined in a Python source file.'
2番目のセルは execfile
を使用して、ノートブックのPythonインタープリター)の.py
ファイルを評価します。
# Bring the file into the local Python environment.
execfile('example.py')
# Call the function defined in the file.
f()
ドライブからcolabノートブックに関数をインポートするには、この関数を試してください。
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!')
次に、次の2つの手順を実行します。1-(package_name.py)というファイルがある場合、それをcolabノートブックコールにアップロードします。
file_name = upload_dir_file(0)
2-次に、パッケージをインポートします。
import package_name
注:同じ機能を使用して、次のことができます。1-ファイル(csv、Excel、pdf、....)のアップロード:
file_name = upload_dir_file(0)
2-ディレクトリとそのサブディレクトリとファイルのアップロード:
dir_name = upload_dir_file(1)
楽しめ!