5

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?

ryantuck
  • 6,146
  • 10
  • 57
  • 71

2 Answers2

4

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.

Prinsig
  • 245
  • 3
  • 9
Josh Lankford
  • 468
  • 2
  • 5
0

Use node's child_process module, and call that from index.html.

Something like:

<!DOCTYPE html>
<html>
  <head>

  </head>
  <body>
    <script>
      var child_process= require('child_process');
      child_process.spawn('python home.py');
    </script>
  </body>
</html>

(Code not tested, example only)

andyhasit
  • 14,137
  • 7
  • 49
  • 51