【问题标题】:In Google's Colab notebook, How do I call a function from a Python file?在 Google 的 Colab 笔记本中,如何从 Python 文件中调用函数?
【发布时间】:2018-04-30 21:32:08
【问题描述】:

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

【问题讨论】:

  • 我的意思是,如果我从 Google Drive 运行笔记本并且我想从文件夹“../tools/my_lib.py”中调用一个函数,在 Jupyter 中我通常会这样做:import sys sys.path.append("../tools/") from my_lib import my_function 我们如何在 Colab 中做到这一点?

标签: google-colaboratory


【解决方案1】:

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

exec(open(filename).read())

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

【讨论】:

    【解决方案2】:

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

    尽情享受吧!

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 谢谢!你的方法确实有效。但是,我实际上的意思是,如果我从 Google Drive 运行一个笔记本并且我会从文件夹“../tools/my_lib.py”中调用一个函数,在 Jupyter 中我通常会这样做:import sys sys.path.append( "../tools/") from my_lib import my_function 我们如何在 Colab 中做到这一点?
      • 感谢您的澄清——我更新了回复以描述如何导入本地定义的模块。如果这不能解决问题,请告诉我。
      • 再次感谢,我想我们快到了! :) 有没有办法让我们使用 Google Drive 中现有的 .py 文件或直接上传它......不知何故不使用“%%writefile”魔法?或者,我们是否必须编写一个脚本来从 Google Drive 中读取并将它们写入本地路径?
      • 同步的脚本是一种选择。另一种方法是使用 FUSE 将驱动器挂载为文件系统。更多详情请见my response to this question
      • 我尝试了您的 FUSE 解决方案。只要我使用绝对路径而不是相对路径,它就可以工作。我会把它算作工作。谢谢,伙计!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-14
      • 1970-01-01
      • 2020-09-10
      • 2020-11-28
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多