【问题标题】:Running python script from MagicMirror module从 MagicMirror 模块运行 python 脚本
【发布时间】:2021-05-30 17:33:59
【问题描述】:

我目前正在为我的魔镜开发一个自定义模块。 我希望这个模块执行 python 脚本。 此 python 脚本从 Web 服务器获取数据并在模块文件夹中创建一个包含数据的 .json 文件。 然后我希望模块在 javascript 中导入这个数据文件并将其显示在屏幕上。

但是我无法让魔镜模块运行 python 脚本。 我对 javascript 的了解很少,因此不胜感激。 这是我到目前为止的代码

  defaults: {
  },
  start: function () {
    var timer = setInterval(()=>{
    const spawn = require('child_process').spawn;
    const childPython = spawn('python3', ['./modules/MMM-Test/bussavganger.py']);
    this.updateDom()
    }, 5000)
  },
  getDom: function() {      
    var element = document.createElement("div")
    element.className = "myContent"
    element.innerHTML = "Hello, everybody!"
    return element
  }
})

目前我只是尝试运行该模块以查看是否创建了 .json 文件。它不是。 如果我单独运行 python 脚本,则会创建文件,所以我知道 .py 文件不是问题。

【问题讨论】:

    标签: javascript dom magic-mirror


    【解决方案1】:

    您尝试通过模块的 js 文件调用 python 脚本,但您应该使用通过 node_helper.js 文件调用 python 脚本。

    所以使用 MagicMirror 的 socketNotification 函数来调用 node_helper 并返回 node_helper 然后调用你的 python 脚本,你可以用它做一些事情,最后将 socketNotification 发送回你的模块的 js 文件,例如。 G。你的 python 程序的结果或退出代码等。

    在您的start: function() 中,您可以通过此命令调用 node_helper,以便您的 python 程序稍后在启动模块后直接由模块助手启动(从现在开始每隔一段时间执行一次):

    var self = this;
    setInterval(function() {
                self.sendSocketNotification('DO_PYTHON', <transmit data for your node_helper here>);
                self.updateDom();
            }, 5000);
    

    在你的模块文件夹中创建一个 node_helper.js 文件,内容如下:

    var NodeHelper = require("node_helper");
    const spawn = require("child_process").spawn;
    
    module.exports = NodeHelper.create({
    
        init() {
        },
    
        start() {
        },
    
        stop() {      
        },
    
        // If notification of the main.js file is received, the node_helper will do this here:
        socketNotificationReceived(notification, payload) {
            if (notification === "DO_PYTHON") {
                // this.config = payload;
                this.yourOwnMethod();
            } else {
                // ...
            }
        },
    
     yourOwnMethod() {
        var self = this;
        var process = spawn("python3", ["/absolute/path/to/modules/MMM-Test/bussavganger.py"]);
        // do something else here
        this.sendSocketNotification("PYTHON_DONE", <e. g. exit state as your payload>)
     },
    

    您也可以在 node_helper.js 中使用 fs 读取您的 json 文件,并在那里对其进行解析并通过 sendSocketNotification 将其发送回。 确保在 node_helper.js 中包含开头的两行和 (!) 重要的始终使用绝对路径

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-25
      • 2021-12-24
      • 2021-11-04
      • 1970-01-01
      相关资源
      最近更新 更多