Uncaught ReferenceError: PythonShell не определен - PythonShell для Nodejs и Electron

Я пытаюсь запустить скрипт python после нажатия кнопки с помощью PythonShell в электронном виде.

У меня есть импорт в main.js, и я вызываю открытие скрипта python через отдельный файл js. Файл имеет форму функции и называется pybutton.js. Файл pybutton.js добавляется через <script> тег через HTML.

Мой 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) 

так что это все еще происходит в строке 8 моего файла pybutton.js выше. Я не должен правильно определять вещи в рендерере.

Используемые модули узлов:

  • Электрон 4.1.2
  • esm 3.2.25
  • Python-оболочка 2.0.3

1 ответ

Вы получаете эту ошибку («PythonShell не определен»), потому что вы действительно не определили и не импортировали пакет PythonShell в свой процесс визуализации.

Вы загружаете PythonShell в свой основной процесс, а затем запускаете BrowserWindow, у которого по умолчанию нет доступа к пакетам узлов. Но, поскольку вы уже изменили это, установив nodeIntegration к true, теперь вы сможете легко импортировать PythonShell в процесс рендеринга вместо основного.

Обратите внимание, что вам также может потребоваться предоставить полный (абсолютный) scriptPath в опциях.

Другие вопросы по тегам