如何在Google Colab中从Google驱动器上的.py文件中导入一个类/函数

huangapple go评论100阅读模式
英文:

How to import a class/function in google Colab from a .py file on google drive

问题

from google.colab import drive
drive.mount('/content/drive')
%cd "/content/drive/MyDrive/Autonomous_Driving/GRTP/clstm_lifelong/us1011/sgan-nsl"
!ls
from model_wcgan_decompose import highwayNet_d

英文:

I am trying to import a class from a .py file which is stored in my google drive.

Initially, I have mounted google drive as follows:

  1. from google.colab import drive
  2. drive.mount('/content/drive')

Then navigate into the destination folder using:

  1. %cd "/content/drive/MyDrive/Autonomous_Driving/GRTP/clstm_lifelong/us1011/sgan-nsl"
  2. !ls

It shows output like:

  1. /content/drive/MyDrive/Autonomous_Driving/GRTP/clstm_lifelong/us1011/sgan-nsl
  2. checkpoint.pkl __pycache__ utils_wcgan_decompose.py
  3. loss.mat trained_models
  4. model_wcgan_decompose.py train_wcgan_decompose.py

Now in that model_wcgan_decompose.py file of the drive there was some class named highwayNet_d, highwayNet_g_compose, highwayNet. Now I am trying to import the class for my purpose using:

  1. from model_wcgan_decompose import highwayNet_d

but it shows error like:

  1. ImportError Traceback (most recent call last)
  2. <ipython-input-26-256c2191a0a5> in <cell line: 9>()
  3. 7 #import model_wcgan_decompose
  4. 8
  5. ----> 9 from model_wcgan_decompose import highwayNet_d
  6. 10
  7. 11
  8. ImportError: cannot import name 'highwayNet_d' from 'model_wcgan_decompose' (/content/drive/MyDrive/Autonomous_Driving/GRTP/clstm_lifelong/us1011/sgan-nsl/model_wcgan_decompose.py)

Please suggest how can I fix it?

答案1

得分: 1

这部分代码描述了如何打开一个文件,使用codecs来读取它,然后使用json加载文件内容,并将其转换为字符串以执行其中的代码。关键部分是将'execution_count'dict中的值从None更改为1(或任何其他想要执行的次数)。以下是这个过程的描述:

  1. import codecs
  2. import json
  3. some_file = codecs.open('/content/drive/My Drive/Colab Notebooks/SomeClass.ipynb', 'r')
  4. some_file = some_file.read()
  5. some_file = json.loads(some_file)
  6. some_file['cells'][0]['execution_count'] = 1
  7. some_code_in_string = ''
  8. for code_in_file in some_file['cells']:
  9. for _code_in_file in code_in_file['source']:
  10. some_code_in_string += _code_in_file
  11. some_code_in_string += '\n'
  12. exec(some_code_in_string)

最后执行代码,并输出结果:

  1. init SomeClass

如果some_file'SomeClass.py'文件,代码会稍微复杂一些,因为需要找到代码的起始位置。以下是这个情况的代码:

  1. import codecs
  2. some_file = codecs.open('/content/drive/My Drive/Colab Notebooks/SomeClass.py', 'r')
  3. some_file = some_file.read()
  4. some_code_in_string = some_file[some_file[some_file.find('https'):].find('"') + 3 + some_file.find('https') + some_file[some_file[some_file.find('https'):].find('"') + 3 + some_file.find('https')].find(' ') + 3:]
  5. exec(some_code_in_string)

执行后,输出结果也为:

  1. init SomeClass

无论如何,最终目标是获取正确格式的some_code_in_string,以便执行其中的代码。

英文:

We can open some_file of code with codecs, use json to load it, and make it string so we can execute some_code_in_string; the important part is that we change the 'execution_count' in its dictionary from None to 1 (or however many times we want it to execute the code).

So here in 'SomeClass.ipynb' I have the following code:

  1. class SomeClass:
  2. def __init__(self):
  3. print(f'init {self.__class__.__name__}')
  4. self.foo = 0
  5. SomeClass()

In another file, we can run:

  1. import codecs
  2. import json
  3. some_file = codecs.open('/content/drive/My Drive/Colab Notebooks/SomeClass.ipynb', 'r')
  4. some_file = some_file.read()
  5. some_file = json.loads(some_file)
  6. some_file['cells'][0]['execution_count'] = 1
  7. some_code_in_string = ''
  8. for code_in_file in some_file['cells']:
  9. for _code_in_file in code_in_file['source']:
  10. some_code_in_string += _code_in_file
  11. some_code_in_string += '\n'
  12. exec(some_code_in_string)

Outputs:

  1. init SomeClass

Now if some_file is 'SomeClass.py' it's a bit trickier since we have to find where the first line of code actually begins:

  1. import codecs
  2. some_file = codecs.open('/content/drive/My Drive/Colab Notebooks/SomeClass.py', 'r')
  3. some_file = some_file.read()
  4. some_code_in_string = some_file[some_file[some_file.find('https'):].find('"') + 3 + some_file.find('https') + some_file[some_file[some_file.find('https'):].find('"') + 3 + some_file.find('https')].find(' ') + 3:]
  5. exec(some_code_in_string)

Outputs:

  1. init SomeClass

Either way, the goal is to get some_code_in_string correctly formatted like:

  1. some_code_in_string = '''
  2. class SomeClass:
  3. def __init__(self):
  4. print(f'init {self.__class__.__name__}')
  5. self.foo = 0
  6. SomeClass()
  7. '''

so that we can execute it.

huangapple
  • 本文由 发表于 2023年4月6日 23:09:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75951065.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定