python 如何从Google Drive上的.py文件导入Google Colab中的类/函数

vmjh9lq9  于 2023-04-10  发布在  Python
关注(0)|答案(1)|浏览(158)

我正试图从存储在我的谷歌驱动器中的.py文件导入一个类。
首先,我安装了Google Drive如下:

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

然后使用以下命令导航到目标文件夹:

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

它显示的输出如下:

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

现在,在驱动器的model_wcgan_decompose.py文件中,有一些名为highwayNet_dhighwayNet_g_composehighwayNet的类。现在我尝试使用以下命令导入类:

from model_wcgan_decompose import highwayNet_d

但它显示错误,如:

ImportError                               Traceback (most recent call last)
<ipython-input-26-256c2191a0a5> in <cell line: 9>()
      7 #import model_wcgan_decompose
      8 
----> 9 from model_wcgan_decompose import highwayNet_d
     10 
     11 

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)

请建议我如何修复它?

bfnvny8b

bfnvny8b1#

我们可以用codecs打开some_file的代码,用jsonload它,并使它成为str ing,这样我们就可以exec ute some_code_in_string;重要的部分是,我们改变了'execution_count'在其dict ionary从None1(或无论多少次,我们希望它执行代码)。
'SomeClass.ipynb'中,我有以下代码:

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

在另一个文件中,我们可以运行:

import codecs
import json

some_file = codecs.open('/content/drive/My Drive/Colab Notebooks/SomeClass.ipynb', 'r')
some_file = some_file.read()
some_file = json.loads(some_file)
some_file['cells'][0]['execution_count'] = 1
some_code_in_string = ''
for code_in_file in some_file['cells']:
    for _code_in_file in code_in_file['source']:
        some_code_in_string += _code_in_file
        some_code_in_string += '\n'
exec(some_code_in_string)

输出:

init SomeClass

现在,如果some_file'SomeClass.py',这有点棘手,因为我们必须在第一行代码实际开始的地方find

import codecs

some_file = codecs.open('/content/drive/My Drive/Colab Notebooks/SomeClass.py', 'r')
some_file = some_file.read()
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:]
exec(some_code_in_string)

输出:

init SomeClass

无论哪种方式,目标都是正确格式化some_code_in_string,如下所示:

some_code_in_string = '''
class SomeClass:
    def __init__(self):
        print(f'init {self.__class__.__name__}')
        self.foo = 0
SomeClass()
'''

这样我们就可以使用它。

相关问题