How to access the Python-Shell output outside the function scope

Asked

Viewed 29 times

0

Hello! I’m making an api using Python in the back-end as the python script is all ok! I will receive a sentence in Javascript and through python-shell I will process it in python, until there is a thousand wonders and everything is going well, as follows the code below:

const {PythonShell} = require('python-shell');

var options = {
    mode: 'text',
    args: ['não gostei do pão']
};

PythonShell.run('my_script.py', options, function (err, result) {
    if (err) throw err;
    
    console.log(result)
});

Where in var options I pass the argument that is the phrase that the backend will process, in this case "I did not like the bread". The whole problem is in the second part of the code

PythonShell.run('my_script.py', options, function (err, result) {
    if (err) throw err;
    
    console.log(result)
});

The result appears in the terminal, but I can’t access it outside the scope of Python-shell.run(), what I’d like to know is how to save the result to a variable that I can use outside the scope. What I’ve tried is this:

const {PythonShell} = require('python-shell');
var resultado

var options = {
    mode: 'text',
    args: ['não gostei do pão']
};

PythonShell.run('my_script.py', options, function (err, result) {
    if (err) throw err;
    
    resultado = result
    //console.log(result)
});

console.log(resultado)

The output on the console is Undefined similarly if you use "Let" and const error saying that there is no initialization method, already giving the console.log(result) within the scope of Pythonshell.run() everything is ok! Only outside does not work kkkkk I imagine it should be something very basic, but I hardly know anything of JS

Thanks in advance for the tips!

  • 1

    Something tells me it’s asynchronous, although I don’t know this package. You can test by doing setTimeout(() => console.log(resultado), 1000), and see if you can.

  • @Miguel The result already appears normally on the console.log() inside Pythonshell, the problem is that I can’t assign it to any variable

  • 1

    I say you go outside, where you got it console.log(resultado), just to test to see if my theory checks out

  • @Miguel that witchcraft was this kkkkkk! Appeared on the console the analysis of the phrase, now what do I do? I’ve lost the line of reasoning kkk

  • you have to make sure that what you want to do with it only happens after (inside that chisel), ex flames a function with the following execution

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.