19

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

4

3 回答 3

19

编辑:如果您想导入本地模块,您需要编辑您的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.'

第二个单元用于在笔记本的 Python 解释器中execfile评估该文件。.py

# Bring the file into the local Python environment.
execfile('example.py')

# Call the function defined in the file.
f()
于 2017-11-17T17:48:01.047 回答
3

请尝试使用此功能将驱动器中的功能导入 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)

好好享受!

于 2018-03-29T13:15:14.787 回答
0

Bob Smith 的答案无法在 colab 中运行。最简单的方法是:

exec(open(filename).read())

适用于所有版本。祝你好运!

于 2020-08-11T11:21:47.400 回答