【发布时间】:2021-06-03 19:02:25
【问题描述】:
在电子中使用 PythonShell 按下按钮后,我正在尝试运行 python 脚本。
我在 main.js 中有我的导入,我通过一个单独的 js 文件调用 python 脚本的打开。该文件为函数形式,名为 pybutton.js。 pybutton.js 文件是通过 HTML 的 <script> 标签添加的。
我的 main.js:
import {app, BrowserWindow} from 'electron'
import {PythonShell} from 'python-shell'
const path = require('path')
let mainWindow
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 1100,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
//DevTools.
mainWindow.webContents.openDevTools()
// Emitted when the window is closed.
mainWindow.on('closed', function () {
mainWindow = null
})
}
// This method will be called when Electron has finished initialization
app.on('ready', createWindow)
// Quit when all windows are closed. additional code for mac yuck.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
app.on('activate', function () {
if (mainWindow === null) createWindow()
})
我的 HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Nexit</title>
<script type="text/javascript" src="main.js"></script>
<script src="js/pybutton.js"></script> -->
</head>
<body>
<p>Text!</p>
<input type="button" class"submit" value="Python" onclick="pybutton()">
<br>
<img id="img" src="">
<img id="imgp" src="">
</body>
</html>
我的 pybutton.js:
function pybutton() {
let options = {
mode: 'text',
pythonOptions: ['-u'], // get print results in real-time
scriptPath: '/../py'
};
PythonShell.run('pybutton.py', options, function (err, results) {
if (err) throw err;
// results is an array consisting of messages collected during execution
console.log('results of pybutton: %j', results);
});
}
当按钮被点击时,我得到这个错误:
Uncaught ReferenceError: PythonShell is not defined
at pybutton (pybutton.js:8)
at HTMLInputElement.onclick (index.html)
如何再次定义 PythonShell?
编辑:这是我的 renderer.js:
import {log} from 'console'
const path = require('path');
log('Hello from the renderer process!')
//-------------------------------------------------------------
import {PythonShell} from 'python-shell';
let {PythonShell} = require('python-shell');
var PythonShell = require('python-shell');
const path = require('path');
然后我添加了
到index.html。
我继续收到同样的错误:
Uncaught ReferenceError: PythonShell is not defined
at pybutton (pybutton.js:8)
at HTMLInputElement.onclick (index.html:21)
所以这仍然发生在我上面的 pybutton.js 的第 8 行。我不能在渲染器中正确定义事物。
使用的节点模块:
- 电子 4.1.2
- esm 3.2.25
- python-shell 2.0.3
【问题讨论】:
标签: javascript python node.js electron es6-modules