Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass function and arguments from node to python, using child_process

I am new to child_process and I want to experiment with its capabilities.

Is there any way to pass a function and arguments to a python file, using spawn (or exec or execFile is spawn cannot do it)?

I want to do something like (pseudocode)

spawnORexecORexefile (python path/to/python/file function [argument1, argument2] ) 

or maybe

spawnORexecORexefile (python path/to/python/file function(argument1, argument2) ) 

Please explain and maybe give an example, because I am a newbie

How I am doing it now?

in node

 var process = spawn('python', [path/to/pythonFile.py, 50, 60] );  

in pythonFile.py

import sys 
import awesomeFile

hoodie = int(sys.argv[1])
shoe = int(sys.argv[2])

awesomeFile.doYourMagic().anotherThing(hoodie, shoe)

as you can see, from node, I send data to pythonFile and then to awesomeFile, to a specific function

I would like to "cut the middle man" and remove the pythonFile and send data from node directly to the awesomeFile file, to a specific function. This is why I am asking

Thanks

like image 850
codebot Avatar asked Jul 17 '20 21:07

codebot


1 Answers

You can run a specific Python function from the command-line using the form python -c 'import foo; print foo.hello()' (from https://stackoverflow.com/a/3987113/5666087).

Place both the files below in the same directory, and run with node index.js. You should see the following output:

Hoodie: 10
Shoe: 15

awesomeFile.py

def myfunc(hoodie, shoe):
    hoodie = int(hoodie)
    shoe = int(shoe)
    print("Hoodie:", hoodie)
    print("Shoe:", shoe)

index.js

const { spawn } = require('child_process');
let hoodie = 10,
    shoe = 15;
const result = spawn("python",
    ["-c", `import awesomeFile; awesomeFile.myfunc(${hoodie}, ${shoe})`])
result.stdout.pipe(process.stdout)
like image 116
jakub Avatar answered Nov 17 '22 05:11

jakub