0

Hi am trying to use a value which I got from a function and wanted to use it outside the function. I have a python script which am trying to call using node and want to use the value returned from python script outside the node function.

Below is what am trying to do, I want the aa value to be used outside function:

PythonShell.run(PythonfilePath, options, function (err, results) {
      if (err)
      throw err;                            
      let aa = parseInt(results)
});
console.log(aa)

I want to use value store in aa for other.

Mohammed
  • 1
  • 2
  • Did you try using `var` instead of `let`. The `let` statement declares a block scope local variable, optionally initializing it to a value. This means the value of **aa** will only be applicable inside the function. You can read this following [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) – Victor G.S. Jun 28 '18 at 08:26
  • 1
    @VictorG.S. `aa` is defined inside the anonymous function. It's local to that function. Using `var` instead of `let` won't change that. – Guillaume Georges Jun 28 '18 at 08:29
  • @GuillaumeGeorges Yes, thank you for the correction. The user needs to initialize a variable globally to use it outside the function. – Victor G.S. Jun 28 '18 at 08:37

3 Answers3

1

There are two issues in your code. The first one is, that you define the variable locally within the anonymous callback function. This way, it will NEVER be visible outside of that function code. You need to declare the variable globally at the top of your code.

But the main issue is: PythonShell.run is an asynchronous function, that calls its callback- function on complete. Your console.log is executed directly after PythonShell.run is called. It does NOT wait for the shell to complete.

You need to read about asynchronous code and callbacks and perhaps about Promises to make your code run.

Without a concrete example of WHAT you want to run after completion there is no way to suggest working code for you.

Tode
  • 11,795
  • 18
  • 34
0

If the function you are calling is synchronous you can declare your variable on top of the function like that:

let aa;

PythonShell.run(PythonfilePath, options, function (err, results) {
  if (err)
  throw err;                            
  aa = parseInt(results);
});
console.log(aa);

A function that accepts a callback if often an asynchronous function. In this case, you can't access the inner variable from the outside. The console.log will be called before the callback completes.

If you need to access this variable you must put your the code requiring it inside the callback function.

Jspdown
  • 424
  • 3
  • 11
0
let aa =  null;

PythonShell.run(PythonfilePath, options, function (err, results) {
      if (err)
      throw err;                            
      aa = parseInt(results)
});
console.log(aa)

you may want to use async - await with this function

rahul
  • 880
  • 3
  • 14
  • 25