Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run python script on node-webkit startup (nw.js)

I have a Python-based app that controls LEDs. It uses Flask to create a webserver so I can work with a nice UI using HTML, CSS, and JS.

My current process:

  1. python home.py
  2. navigate to localhost:5000 in browser
  3. profit!

I'd like to take it a step further and package it up as a nw.js (formerly node-webkit) app.

Basically, I believe I simply need to execute my python script before the window loads, so that my tried-and-true flask web server kicks off and creates a localhost:5000 page for my nw.js app interface to open up.

How can I package my nw.js app so it runs a python script on startup?

like image 817
ryantuck Avatar asked Oct 19 '22 16:10

ryantuck


1 Answers

You can create a loading page and render the actual app after the web server has started.

package.json:

{
  "name": "pythonApp",
  "version": "0.0.0",
  "main": "loading.html",
  "window": {
    "title": "App Name",
    "width": 800,
    "height": 600,
    "position": "center",
  }
}

The loading page (loading.html) will load a js file that launches your actual application page as a hidden window and you can then show it when the server is running.

loading.html:

var gui = require('nw.gui');

var currentWindow = gui.Window.get(); // Get reference to loading.html

var exec = require('child_process').execFile;
exec('home.py', {cwd:'.'}, function (error, stdout, stderr){ // Runs your python code
  var appWindow = gui.Window.open('app.html', // Starts your application
    { width: 800,
      height: 600,
      position: 'center',
      focus: false,
      transparent: true // This hides the application window
    }
);
appWindow.on('loaded', function() { // Waits for application to be loaded
  currentWindow.close({force: 'true'}); // Closes loading.html
    appWindow.show();  // Shows app.html
    appWindow.focus(); // Set the focus on app.html
  });
});

Anyway that is the gist of it, but you may need to make changes for your particular setup. Hope it helps.

like image 162
Josh Lankford Avatar answered Oct 22 '22 07:10

Josh Lankford