在 node.js 中使用 child_process.spawn 通过 Electron 应用程序 (node.js) 执行 python 脚本。如果我在终端 (macOS) 上运行 python 脚本没有问题,但是,使用 node.js 和:
const spawn = require('child_process').spawn
let ls = spawn('python', ['runserver.py','--help'], {
cwd: __dirname,
detached: true
})
我从模块导入失败的 python 中得到错误,例如:
Traceback (most recent call last):
File "runserver.py", line 17, in <module>
from queue import Queue
ImportError: No module named queue
我已经尝试过设置不同的环境,但没有成功。
编辑:
这是sys.path的日志:
通过
child_process执行代码[ '/Users/xAlien95/Desktop/test.app/Contents/Resources/app', '/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/Library/Python/2.7/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC' ]通过终端执行代码
[ '/Users/xAlien95/Desktop/test.app/Contents/Resources/app', '/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/site-packages', '/usr/local/Cellar/protobuf/3.1.0/libexec/lib/python2.7/site-packages' ]
因此,它在终端中使用下载的 homebrew Python 框架。我如何确保在 node.js 应用程序中发生同样的情况?
请您参考如下方法:
让 python 查找不同库的一种方法是使用环境变量 PYTHONPATH。您可以使用 process.env.PYTHONPATH
对于想要运行 homebrew 安装的 python 的特定情况,python 可执行文件应位于:
let ls = spawn(process.env.HOMEBREW_PREFIX + '/bin/python', ['runserver.py','--help'], {
...
如果 HOMEBREW_PREFIX 在 process.env 中不可用,并且所需 python 的路径已知,则可以将其硬编码到 spawn 中:
let ls = spawn(/*<Where my python lives>*/ + '/bin/python', ['runserver.py','--help'], {
...
