【发布时间】:2019-11-04 05:16:22
【问题描述】:
我正在创建一个使用 Python 3.7 编写的后端的库存应用程序。我正在使用 Electron 为其构建 GUI,并使用 Node.js 模块“python-shell”来与 Python 代码进行通信。我希望 python-shell 的所有代码都在一个单独的 JavaScript 文件(connector.js)中。如果我从命令行仅使用 node 运行该文件,它工作得非常好,但从 HTML Button 调用该函数不起作用。
我知道 Electron nodeIntegration 的最新更新之一默认为 false,但我确实将其设置为 true。不幸的是,它仍然不允许我与 Electron 渲染器进程中的 Node 模块进行通信。如果我将 connector.js 代码复制到 Electron 使用的 main.js 文件中并在应用程序启动时调用它,它确实可以工作,但使用 HTML 按钮调用它显然也不起作用。
这是 Electron 的 main.js 文件,其中 nodeIntegration 设置为 true。
const {app, BrowserWindow, Menu} = require('electron')
const fs = require('fs')
let mainWindow
function createWindow() {
mainWindow = new BrowserWindow({
// Set fixed size of main window
width: 1280,
height: 768,
resizable: false,
webPrefrences: {
nodeIntegration: true,
}
})
mainWindow.loadFile('./main.html')
mainWindow.on('closed', function () {
mainWindow = null
})
//Opens the dev tools by default.
mainWindow.webContents.openDevTools();
}
// Disable the default Menu Bar
Menu.setApplicationMenu(null)
app.on('ready', createWindow)
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
app.on('activate', function () {
if (mainWindow === null) createWindow()
})
这是使用正确参数调用 Python 脚本的 connector.js 文件。功能.py 用于测试一个非常简单的脚本,该脚本采用第一个命令行参数(在本例中为addNewDataset)来调用函数,第二个作为它创建的文件的名称。
const {PythonShell} = require('python-shell')
var options = {
mode: 'text',
encoding: 'utf8',
pythonPath: 'python3',
pythonOptions: ['-u'],
scriptPath: './',
args: ['addNewDataset', 'testDataset123']
};
function test() {
PythonShell.run('functionality.py', options, function (err) {
if (err) throw err;
console.log('done');
});
}
使用简单的脚本标签将其加载到 HTML 文件中
<script src="connector.js"></script>
并使用输入调用
<input type="submit" value="Button" onclick="test()">
我很确定我只是误解了 Electron 以及主进程和渲染器进程的工作方式。不幸的是,无论我在 Internet 上寻找什么,我似乎都无法获得真正有效的解决方案。
【问题讨论】:
-
是
webPreferences,不是webPrefrences,好像漏掉了e...
标签: javascript python node.js electron