no print statement from pyton to node console
Describe the bug tried while loop to get print statement but to realtime console log of the print statemnt.
pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
});
this give print statement after code after completion.
Python code
print("hello, world")
Javascript code
//Import express.js module and create its variable.
import express from "express";
const app = express();
//Import PythonShell module.
import { PythonShell } from "python-shell";
//Router to handle the incoming request.
app.get("/", (req, res, next) => {
//Here are the option object in which arguments can be passed for the python_test.js.
let options = {
mode: "text",
pythonOptions: ["-u"], // get print results in real-time
// scriptPath: "", //If you are having python_test.py script in same folder, then it's optional.
args: ["shubhamk314"], //An argument which can be accessed in the script using sys.argv[1]
};
PythonShell.run("python_test.py", options, function (err, result) {
if (err) throw err;
// result is an array consisting of messages collected
//during execution of script.
console.log("result: ", result.toString());
res.send(result.toString());
});
});
//Creates the server on default port 8000 and can be accessed through localhost:8000
const port = 8000;
app.listen(port, () => console.log(`Server connected to ${port}`));
Expected behavior should have gotten the hellow, world at the bash terminal of the server code.
Actual behavior nothing happened/showing...
Other Information (please complete the following information):
- OS: [e.g. Windows11]
- Python Version [e.g. 3.6]
- Node Version [e.g. 21]
Additional context Add any other context about the problem here.
let options = {
mode: "json",
pythonOptions: ["-u"], // get print results in real-time
// scriptPath: "", //If you are having python_test.py script in same folder, then it's optional.
args: ["arguments"], //An argument which can be accessed in the script using sys.argv[1]
};
let pyshell = new PythonShell("python_test.py", options);
pyshell.on("message", function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
});
This work as expected, getting realtime print statement
This is intentional, but I see why you are confused because the readme does not have a good example. As you found out you can use pyshell.on("message" with -u to give you real time print results.