在 nodejs 中从 python 激活虚拟环境

Activating an virtual environment from python in nodejs

我在 raspberry pi 4 上有以下项目: 我在 python 中创建了一个人脸识别脚本,它需要一个 运行 的虚拟环境。 该脚本打印出已检测到的人。

在 NodeJS 中,我想通过 运行在节点(缩小版)中运行脚本来接收答案:

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');


 });

});

执行代码时,我立即得到一个 "python ended"。

在我的 pi 上,当我 运行 在执行之前执行以下命令时,我可以 运行 脚本:

source ~/.virtualenvs/cv2_env/bin/activate 

python脚本基本上是:

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

更新

当运行宁

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

我收到以下错误:

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)

这是我的文件系统:

我做错了什么?

激活虚拟环境必须在脚本中完成。之外的将不会生效。

与答案 类似,您只想执行虚拟环境中列出的 Python 运行时。该问题引用 pip 但您基本上可以将其替换为您想要的 Python 版本(存在于您的虚拟环境中)。换句话说,您将替换此行:

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

这一行:

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

注意: 如果失败,您可能需要将 /home/youruser/.virtualenvs/cv2_env/bin/python 更改为您正在寻找的 Python 的任何版本,例如/home/youruser/.virtualenvs/cv2_env/bin/python3/home/youruser/.virtualenvs/cv2_env/bin/python3.7.