Node.jss python child script outputting on finish, not real time

2024/10/3 14:18:34

I am new to node.js and socket.io and I am trying to write a small server that will update a webpage based on python output.

Eventually this will be used for a temperature sensor so for now I have a dummy script which prints temperature values every few seconds:

Thermostat.py

import random, time
for x in range(10):print(str(random.randint(23,28))+" C")time.sleep(random.uniform(0.4,5))

Here's a cut down version of the server:

Index.js

var sys   = require('sys'), spawn = require('child_process').spawn, thermostat = spawn('python', ["thermostat.py"]),app = require('express')(),http = require('http').Server(app),io = require('socket.io')(http);thermostat.stdout.on('data', function (output) { var temp = String(output);console.log(temp);io.sockets.emit('temp-update', { data: temp});
}); app.get('/', function(req, res){res.sendFile(__dirname + '/index.html');});

And finally the web page:

Index.html

<!doctype html>
<html><head><title>Live temperature</title><link rel="stylesheet" type="text/css" href="styles.css"></head><body><div id="liveTemp">Loading...</div><script src="http://code.jquery.com/jquery-1.11.1.js"></script><script src="/socket.io/socket.io.js"></script><script>var socket = io();socket.on('temp-update', function (msg) {$('#liveTemp').html(msg.data)});</script></body>
</html>

The problem is nodejs seems to recieve all of the temperature values at once, and instead of getting 10 temperature values at random intervals, I get all of the values in one long string after the script has finished:

lots of temp values console output

Answer

You need to disable output buffering in python. This can be done many different ways, including:

  • Setting the PYTHONUNBUFFERED environment variable
  • Passing the -u switch to the python executable
  • Calling sys.stdout.flush() after each write (or print() in your case) to stdout
  • For Python 3.3+ you can pass flush=true to print(): print('Hello World!', flush=True)

Additionally, in your node code, (even though you have a sleep in your python code and you are now flushing stdout) you really should not assume that output in your 'data' handler for thermostat.stdout is always going to be just one line.

https://en.xdnf.cn/q/70719.html

Related Q&A

lambda function returning the key value for use in defaultdict

The function collections.defaultdict returns a default value that can be defined by a lambda function of my own making if the key is absent from my dictionary.Now, I wish my defaultdict to return the u…

Calling Matlab function from python

I have one project in which I have one one matlab code which I have to run tho Django. I tried installing Mlabwrap ..But it gives me following error.Traceback (most recent call last): File "<st…

Suds ignoring proxy setting

Im trying to use the salesforce-python-toolkit to make web services calls to the Salesforce API, however Im having trouble getting the client to go through a proxy. Since the toolkit is based on top of…

CSV to JSON script

I took this script from here: import csv from itertools import izip f = open( /django/sw2/wkw2/csvtest1.csv, r ) reader = csv.reader( f ) keys = ( "firm_url", "firm_name", "fir…

Accessing an ALREADY running process, with Python

Question: Is there a way, using Python, to access the stdout of a running process? This process has not been started by Python.Context: There is a program called mayabatch, that renders out images fro…

sum up two pandas dataframes with different indexes element by element

I have two pandas dataframes, say df1 and df2, of some size each but with different indexes and I would like to sum up the two dataframes element by element. I provide you an easy example to better und…

Urwid: make cursor invisible

Im using urwid, which is a Python "framework" for designing terminal user interfaces in ncurses. Theres one thing though that Im not able to do in urwid that was easy in curses - make the cur…

How do I use scipy.weave.inline together with external C libraries?

I am trying to understand weave.inline to wrap C code in my Python programs. The code below simply takes the Numpy array and multiplicates all of its elements by 2.inl.py import numpy import scipy.weav…

sqlalchemy multiple foreign keys to same table

I have a postgres database that looks something like this:Table "public.entities"Column | Type | Modifiers ---------------+---…

Django - Return a file from Root folder via a URL

I purchased a SSL cert online and now ind the mid of verifying my host. How it works is:It gives me a file I have to make that file accessible through a specific URL on my host. If the content of the f…