在 Google 的 Colab 笔记本中,如何从 Python 文件中调用函数?

In Google's Colab notebook, How do I call a function from a Python file?

我想从 Colab 笔记本调用我在单独的 python 文件中编写的 python 函数。我该怎么做?

编辑:如果您想导入一个本地模块,您需要编辑您的 sys.path 以指向那个新目录。这是一个示例笔记本: https://colab.research.google.com/notebook#fileId=1PtYW0hZit-B9y4PL978kV2ppJJPhjQua

原回复: 当然,这是一个示例笔记本: https://colab.research.google.com/notebook#fileId=1KBrq8aAiy8vYIIUiTb5UHG9GKOdEMF3n

有两个单元格:第一个单元格定义了一个 .py 文件,其中包含要导入的函数。

%%writefile example.py
def f():
  print 'This is a function defined in a Python source file.'

第二个单元格使用 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!')

然后按照以下两步操作: 1- 如果您有一个名为 (package_name.py) 的文件,要将其上传到您的 colab notebook,请调用:

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)

尽情享受吧!

Bob Smith 的回答不可能 运行 在 colab 中。 最简单的方法是:

exec(open(filename).read())

适合所有版本。祝你好运!