3

I've this simple Python script print out a message every second:

#!/usr/bin/python
import time

while True:
    print u"Message"
    time.sleep(1)

I'm trying to integrate a 3rd party Python script with the above structure with Node.js using python-shell.

I'm having this JS script to get all messages from the Python script:

var PythonShell = require('python-shell');

var options = {
  scriptPath: './'
};

var pyshell = new PythonShell('test.py',options);

pyshell.on('message', function (message) {
  // received a message sent from the Python script (a simple "print" statement) 
  console.log(message);
});

// end the input stream and allow the process to exit 
pyshell.end(function (err) {
  if (err) throw err;
  console.log('finished');
});

But it seems, that the while True in Python cause that the on-event is not called. How can I solve this? Can I change the loop inside the Python script to something compatible with python-shell?

2
  • the while True in Python cause that the on-event is not called - True. Its an infinite loop. How can I solve this? - Remove the infinite loop. Commented Mar 22, 2015 at 15:52
  • My 3rd party python script is designed to run in an infinite loop checking state of some device. Commented Mar 22, 2015 at 15:56

1 Answer 1

6

You need to flush sys.stdout as the output is buffered because it is piped:

import time
import sys
while True:
    print u"Message"
    sys.stdout.flush()
    time.sleep(1)

You will receive the output immediately once flushed:

$ nodejs n.js
Message
Message
Message
.....

You may be able to set the buffering to line buffered or unbuffered when you start the shell but I am not overly familiar with nodejs.

There is actually a way to set the -u flag to get unbuffered output with the pythonOptions flag:

var PythonShell = require('python-shell');

var pyshell = new PythonShell('test.py',{scriptPath:"./", pythonOptions: ['-u']});

pyshell.on('message', function (message) {
  // received a message sent from the Python script (a simple "print" statement) 
  console.log(message);

});

// end the input stream and allow the process to exit 
pyshell.end(function (err) {
  if (err) throw err;
  console.log('finished');
});

The output will be unbuffered so there will be no need to flush stdout.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer. Works great! But how can I exit the infinite loop with nodejs?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.