Skip to content

sending message to python from node.js using python-shell without terminating the python script #260

Open
@8ahmedanwer8

Description

@8ahmedanwer8

i am doing some communication between electron.js/node.js and python. i can run a file from python and send a message to it, which is capture via stdin, and that python file can print my message to the electron console. but, this only seems to work if i terminate the program after sending my message in node whereas, i want send the message while the program is running.

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

pyshell.send(JSON.stringify([1,2,3,4,5]));

pyshell.on('message', function (message) {
    console.log(message);
});

pyshell.end(function (err) {
    if (err){
        throw err;
    };

    console.log('finished');
});
import sys, json

#Read data from stdin
def read_in():
    lines = sys.stdin.readlines()
    return json.loads(lines[0])

def main():

    lines = sys.stdin.readlines()
    lines = json.loads(lines[0])

    total_sum_inArray = 0
    for item in lines:
        total_sum_inArray += item
    print (lines)


main()

my output is [1,2,3,4,5] as it should be, but when i remove pyshell.end listener in the node code, i don't get any output in the console. i'm not sure how sys and stdin exactly work so maybe that's why i cannot figure this out. also, this is my first time asking a question on github so a bit nervous hehe.
thanks for any guidance.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions