GwiHwan Go
GwiHwan Go

Reputation: 51

nodejs PythonShell, how to export variables in run function

I want to export variable named completed so that I can use this out of PythonShell.run function. Is there any suggestion? here's my code.

python code

#test.py
import sys

def hello(a,b):
    print("hello and that's your sum:", a + b)

if __name__ == "__main__":
    a = int(sys.argv[1])
    b = int(sys.argv[2])
    hello(a, b)

javascript code

let {PythonShell} = require('python-shell')

let options = {
    mode: 'text',
    pythonOptions: ['-u'], // get print results in real-time
    args: [1414, 2323]
  };

PythonShell.run('./photos/filterPhoto/test.py', options, function (err, results) {
    if (err) throw err;
    const completed = results; 
///results: ["hello and that's your sum: 3737"]
  });

console.log(completed)



Error : ReferenceError: completed is not defined

Upvotes: 0

Views: 352

Answers (1)

Extreme
Extreme

Reputation: 364

Try using JSPyBridge/pythonia to call the Python script:

Through ES6 imports:

import { python } from 'pythonia'
const test = await python("./test.py")
await test.hello(2, 3)
python.exit()

Or through CommonJS imports:

const { python } = require('pythonia')
async function main() {
  const test = await python("./test.py")
  await test.hello(2, 3)
}
main().then(() => python.exit())

Upvotes: 2

Related Questions