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

时间:2017-11-17 07:01:13

标签: google-colaboratory

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

3 个答案:

答案 0 :(得分:16)

修改:如果您要导入本地模块,则需要编辑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()

答案 1 :(得分: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笔记本电话:

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)

享受它!

答案 2 :(得分:0)

鲍勃·史密斯(Bob Smith)的答案无法在合作实验室中找到。 最简单的方法是:

exec(open(filename).read())

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