1

I have a python program and I want to print the output of that program on an HTML page using Node JS. The python script is being called using 'child_process'. I want to print the value of 't' on HTML page. Is there any way to do it?

script.py

import time

t=0
def main():
    while 1:
        t =t+1
        print t
        time.sleep(2)

# Start process
if __name__ == '__main__':
    main()

Here I want to print the value of 't' after every 2 seconds.

app.js

var sys =require('sys');
var myPythonScript ="script.py";
var path =resolve("C:\\Python27\\python.exe");
var pythonExecutable = path;

const spawn = require('child_process').spawn;
const scriptExecution = spawn(pythonExecutable, [myPythonScript]);

scriptExecution.stdout.on('data', (data) => {
    console.log(data);
});
});

This JS function is called when a button is clicked on the HTML page.

Amit Naik
  • 121
  • 2
  • 17

3 Answers3

0

I have an idea for you- you can create a simple flask app (http://flask.pocoo.org/), that will listen to a specific port. When this app will receive a REST API request, it will execute your's python code and return the result as a response. In the javascript side, you will only need to create an ajax request which will provide the request to the flask app.

In this way, you can mix both python and javascript comfortably.

Yuval Pruss
  • 8,716
  • 15
  • 42
  • 67
  • I don't want to execute it on flask because the rest of my code and other functionalities are on Node JS. Is there anyway to do this using javascript in Node JS? – Amit Naik Mar 18 '17 at 15:28
0

you can use urllib to send the output of your .py file :

import urllib

output="test"
url="post.php" 

param=urllib.urlencode({'output':output})  
urllib.urlopen(url,param)

to get the post in PHP :

<?php

    $output = $_POST["output"];
    echo $output;    

?>

to get the post parameter in Node.js you can read this :

https://scotch.io/tutorials/use-expressjs-to-get-url-and-post-parameters

How do you extract POST data in Node.js?

https://dzone.com/articles/get-post-parameter-nodejs

Community
  • 1
  • 1
Aominé
  • 472
  • 3
  • 11
0

Yes, you can code on python then using rapydscript and npm you can convert python code to Js code and it will print on the HTML page. The best part of rapydscript is, it doesn't need any server.

For example: Below code is an alert function in python:

def greet():
    alert("Hello World!")

This will convert to below Js code:

function greet() {
    alert("Hello World!");
}

https://www.npmjs.com/package/rapydscript-ng

Karpi
  • 116
  • 8