如何在google colaboratory中导入python文件?

时间:2018-03-07 11:46:24

标签: python google-colaboratory

我正在尝试在Google Colab上运行我的程序;我的代码使用单独写的.py文件。

在普通系统中,我将所有文件放在一个文件夹中,并使用package com.gbids.mqtt.moquette.main; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; public class ClientLauncher { private static final String content = "{\"randomData\": 25}"; private static final String willContent = "Client disconnected unexpectedly"; private static final String broker = "tcp://0.0.0.0:1883"; private static final String clientIdPrefix = "client"; public static void main(String[] args) throws Exception{ sendDataWithQOSOne(); System.exit(0); } private static void sendDataWithQOSOne(){ try { final String clientId = "client_1"; MqttClient sampleClient = new MqttClient(broker, clientId, new MemoryPersistence()); MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setCleanSession(false); // for publisher - this is not needed I think sampleClient.connect(connOpts); MqttMessage message = new MqttMessage(content.getBytes()); message.setQos(1); final String topic = "devices/reported/" + clientId; sampleClient.publish(topic, message); System.out.println("Message published from : " + clientId + " with payload of : " + content); sampleClient.disconnect(); } catch (MqttException me) { me.printStackTrace(); } } } ,但是当我尝试在Google云端硬盘中使用相同的文件夹时,会出现导入错误。

4 个答案:

答案 0 :(得分:4)

如果你只有2-3个文件,你可以尝试我在另一个问题中给出的解决方案。

Importing .py files in Google Colab

但如果您有5-10个文件,我建议您将您的库放在github上,然后将!git clone放到Google Colab上。另一个解决方案是压缩所有库文件,然后通过解压缩!unzip mylib.zip

来修改第一个解决方案

如果这些库文件不在文件夹结构中,则只有同一文件夹中的几个文件。您可以上传并保存它们然后导入它们。上传时间:

def upload_files():
  from google.colab import files
  uploaded = files.upload()
  for k, v in uploaded.items():
    open(k, 'wb').write(v)
  return list(uploaded.keys())

答案 1 :(得分:1)

现在在googlecolab(11月18日)中,您可以轻松上传python文件

  • 导航到文件(在左侧面板中显示)
  • 点击“上传”,上传python文件夹或.py文件
  • 使用googlecolab图书访问文件。

请在下面查看我的屏幕截图! enter image description here

答案 2 :(得分:0)

例如,您有一个像这样的模块

simple.py
def helloworld():
   print("hello")

单击左侧面板上的箭头=>选择“文件”选项卡=>上传simple.py 在这样的笔记本代码中

import simple
simple.helloworld()
=> hello

答案 3 :(得分:0)

当我有多个python脚本并且想要通过代码自动导入时,我使用的某些方法是将其设置为一个程序包并从仓库中克隆。

首先(显然)首先在包含setup.py__init__.py文件的仓库中设置脚本。

然后将其添加到笔记本顶部:

!rm -rf <repo-name>  # in case you need to refresh after pushing changes 
!git clone https://github.com/<user>/<repo-name>.git

然后安装软件包:

!pip install ./<repo-name>

现在方便地导入函数或其他任何东西:

from <app-name>.<module> import <function>