Search code examples
pythonnode.jsraspberry-pivirtual-environment

Activating an virtual environment from python in nodejs


I have following project on a raspberry pi 4: I created a face recognition script in python which needs an virtual enviroment to run. The script prints out the person which has been detected.

In NodeJS I want to receive the answer by running the script in node (minified version):

const http = require("http");
const server = http.createServer((req, res) => {

var spawn = require('child_process').spawn,
py    = spawn('python', ['faceReg.py'],)
py.stdout.on('data', function(data){
  console.log('Data:' + data);

});
py.stdout.on('end', function(){
  console.log('Python ended');


 });

});

When executing the code I get immdeaitly an "python ended".

On my pi I can run the script when I run following command before execution:

source ~/.virtualenvs/cv2_env/bin/activate 

The python script is basicly:

stop = False
while(stop==False):
   print("Peter")

Update

When running

py    = spawn('~/.virtualenvs/cv2_env/bin/python', ['faceReg.py'])

I get following error:

events.js:174
      throw er; // Unhandled 'error' event
      ^
Error: spawn ~/.virtualenvs/cv2_env/bin/python ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
    at onErrorNT (internal/child_process.js:415:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)
    at Function.Module.runMain (internal/modules/cjs/loader.js:757:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
Emitted 'error' event at:
    at Process.ChildProcess._handle.onexit (internal/child_process.js:246:12)
    at onErrorNT (internal/child_process.js:415:16)
    [... lines matching original stack trace ...]
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

This is my file system: enter image description here

What am I doing wrong?


Solution

  • Activating the virtual environment must be done in the script itself. Outside of that will not take effect.

    Similar to the answer here, you'll just want to execute the Python runtime that's listed in your virtual environment. That question references pip but you can essentially just replace it with the version of Python you want (that exists in your virtual environment). In other words, you would replace this line:

    py    = spawn('python', ['faceReg.py'],)
    

    With this line:

    py    = spawn('/home/youruser/.virtualenvs/cv2_env/bin/python', ['faceReg.py'],)
    

    Note: If this fails, you may need to change /home/youruser/.virtualenvs/cv2_env/bin/python to be whatever version of Python you're looking for e.g. /home/youruser/.virtualenvs/cv2_env/bin/python3 or /home/youruser/.virtualenvs/cv2_env/bin/python3.7.