【发布时间】:2020-03-17 04:16:05
【问题描述】:
我正在使用 Electron 创建一个桌面应用程序。当我单击应用程序上的按钮(由 HTML 制成)时,我正在尝试运行 Python 脚本。我通过使用child_process 和spawn 做到了这一点。但是,当我在目录中使用命令提示符(Windows 10)运行npm start 时,我从renderer.js 得到document is not defined。
我知道在 Electron 中使用 ipcMain 和 ipcRenderer 有一些好处,但我不确定如何使用它。任何帮助表示赞赏。
这是我的文件夹树:
.
├── hello.py
├── index.html
├── main.js
├── node_modules
│ // node modules
├── package-lock.json
├── package.json
├── renderer.js
└── require.js
index.html:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="require.js"></script>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="require.js"></script>
<button id="push_me" type="button">Push me</button>
</body>
</html>
main.js:
const {app, BrowserWindow} = require('electron');
const path = require('path');
const url = require('url');
require('./renderer.js');
let win;
function createWindow() {
win = new BrowserWindow({width: 800, height: 600, webPrefences: {nodeIntegration: true}});
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
win.on('closed', () => {
win = null;
})
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
})
renderer.js:
var pushMe = document.getElementById('push_me');
pushMe.addEventListener('click', runPython());
function runPython() {
var python = require(['child_process']).spawn('python', ['hello.py']);
python.stdout.on('data', function(data) { console.log(data.toString('utf8')); });
}
hello.py:
print("Hello, world!")
package.json:
{
"name": "app_ui",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"author": "",
"license": "ISC",
"dependencies": {
"electron": "^8.1.1",
"jquery": "^3.4.1",
"python-shell": "^1.0.8"
}
}
【问题讨论】:
标签: javascript html electron