集成挑战:Electron、SQLite 和 Python - 寻求帮助

Integration Challenges: Electron, SQLite, and Python - Seeking Assistance

提问人:Anderson Ferreira 提问时间:11/17/2023 最后编辑:Anderson Ferreira 更新时间:11/17/2023 访问量:46

问:

我在我的应用程序中将 Electron 与 SQLite 和 Python 集成时遇到了困难。该应用程序有一个窗口,用于将数据保存在 SQLite 数据库中,然后运行 Python 脚本。Python 执行按预期工作;但是,保存到 SQLite 并未按计划进行。

问题描述:

  • 窗口创建成功。
  • Python 脚本正常运行。

但是,保存到 SQLite 的事件似乎不起作用。

法典:

main.js:

const { app, BrowserWindow, ipcMain } = require('electron');
const { spawnSync } = require('child_process');
const path = require('path');
const { Database } = require('sqlite3').verbose();

function createWindow() {
  const window = new BrowserWindow({ width: 800, height: 600 });
  window.loadFile('index.html');

  console.log('Window created.');

  // Handle the event to save to SQLite and execute the Python script
  ipcMain.on('saveAndExecute', (event, data) => {
    console.log('Receiving data to save to SQLite and execute the Python script:', data);
    saveToSQLiteAndExecuteScript(data);
  });
}

function saveToSQLiteAndExecuteScript(data) {
  console.log('Starting the operation to save to SQLite...');

  // Connect to the SQLite database
  const db = new Database(path.join(__dirname, 'mydatabase.db'));

  // Create a table if it doesn't exist
  db.run('CREATE TABLE IF NOT EXISTS entries (text TEXT)');

  // Insert data into the table
  const stmt = db.prepare('INSERT INTO entries (text) VALUES (?)');
  stmt.run(data, function (err) {
    if (err) {
      console.error('Error inserting data into SQLite:', err.message);

      // Display the error log but continue with the execution of the Python script
      console.log('Continuing with the execution of the Python script...');
      executePythonScript();
    } else {
      console.log('Data inserted into SQLite successfully!');
      // Finalize the statement execution and close the database connection
      stmt.finalize();
      db.close();

      // Execute the Python script after successful SQLite operation
      executePythonScript();
    }
  });
}

function executePythonScript() {
  console.log('Executing the Python script...');

  const pythonExecutable = 'C:\\Users\\Gustavo\\AppData\\Local\\Programs\\Python\\Python312\\python.exe';
  const pythonScriptPath = path.join(__dirname, 'hello.py');

  const result = spawnSync(pythonExecutable, [pythonScriptPath], { encoding: 'utf8' });

  if (result.error) {
    console.error('Python script error:', result.error);
  } else {
    console.log('Python script output:', result.stdout);
  }
}

app.on('ready', createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

渲染器.js:

// Add the following at the top of the file
const { ipcRenderer } = require('electron');

document.addEventListener('DOMContentLoaded', () => {
  const textInput = document.getElementById('textInput');
  const saveAndExecuteButton = document.getElementById('saveAndExecuteButton');

  console.log('Page loaded.');

  // Add an event listener for the save and execute button
  saveAndExecuteButton.addEventListener('click', () => {
    console.log('Save and execute button pressed.');

    const inputData = textInput.value;

    // Send data to the main process to save to SQLite and execute the Python script
    ipcRenderer.send('saveAndExecute', inputData);
  });
});

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello Python from Electron!</title>
  </head>
  <body>
    <h1>Hello Python!</h1>
    
    <textarea id="textInput" rows="4" cols="50" placeholder="Type something..."></textarea>
    <br>
    <button id="saveButton">Save to SQLite</button>

    <script src="./renderer.js"></script>
  </body>
</html>

我在UI中的错误日志:

未捕获的 ReferenceError:未定义 require 在渲染器.js:3:25

我不知道还能做些什么来完成这项工作。请帮忙!

我尝试更改如何导入和编辑函数的执行顺序,但收效甚微。我的代码只需要在 inputText 中使用从 UI 接收的文本创建一个数据库,然后执行 Python 脚本。就是这样,但它根本不起作用!

好的,现在我的主要.js是:

const { app, BrowserWindow, ipcMain } = require('electron');
const { spawnSync } = require('child_process');
const path = require('path');
const { Database } = require('sqlite3').verbose();

function createWindow() {
  const window = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      preload: path.join(__dirname, 'preload.js')
    }
  });

  window.loadFile('index.html');

  console.log('Window created.');

  // Handle the event to save to SQLite and execute the Python script
  ipcMain.on('saveAndExecute', (event, data) => {
    console.log('Received data to save to SQLite and execute the Python script:', data);
    saveToSQLiteAndExecuteScript(data);
  });
}

function saveToSQLiteAndExecuteScript(data) {
  console.log('Initiating the operation to save to SQLite...');

  // Connect to the SQLite database
  const db = new Database(path.join(__dirname, 'mydatabase.db'));

  // Create a table if it doesn't exist
  db.run('CREATE TABLE IF NOT EXISTS entries (text TEXT)');

  // Insert data into the table
  const stmt = db.prepare('INSERT INTO entries (text) VALUES (?)');
  stmt.run(data, function (err) {
    if (err) {
      console.error('Error inserting data into SQLite:', err.message);

      // Display the error log but continue with the execution of the Python script
      console.log('Continuing with the execution of the Python script...');
      executePythonScript();
    } else {
      console.log('Data inserted into SQLite successfully!');
      // Finalize the statement execution and close the database connection
      stmt.finalize();
      db.close();

      // Execute the Python script after successful SQLite operation
      executePythonScript();
    }
  });
}

function executePythonScript() {
  console.log('Executing the Python script...');

  const pythonExecutable = 'C:\\Users\\Gustavo\\AppData\\Local\\Programs\\Python\\Python312\\python.exe';
  const pythonScriptPath = path.join(__dirname, 'hello.py');

  const result = spawnSync(pythonExecutable, [pythonScriptPath], { encoding: 'utf8' });

  if (result.error) {
    console.error('Error from the Python script:', result.error);
  } else {
    console.log('Output from the Python script:', result.stdout);
  }
}

app.on('ready', createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

我的渲染器.js:

// renderer.js
document.addEventListener('DOMContentLoaded', () => {
    const textInput = document.getElementById('textInput');
    const saveAndExecuteButton = document.getElementById('saveAndExecuteButton');
  
    console.log('Page loaded.');
  
    // Add an event listener for the save and execute button
    saveAndExecuteButton.addEventListener('click', () => {
      console.log('Save and execute button pressed.');
  
      const inputData = textInput.value;
  
      // Use electronAPI to send data to the main process
      electronAPI.sendToMain('saveAndExecute', inputData);
    });
  });
  

和我的预加载.js:

// preload.js
const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
  sendToMain: (channel, data) => {
    ipcRenderer.send(channel, data);
  },
  receiveFromMain: (channel, func) => {
    ipcRenderer.on(channel, (event, ...args) => func(...args));
  },
});

我在UI中获取日志:

未捕获的 TypeError:无法读取 null 的属性(读取“addEventListener”) 在 HTMLDocument。(渲染器.js:9:26)

javascript python 请求 电子

评论

0赞 Timur 11/17/2023
您可以尝试在 main.js 中添加到 BrowserWindow 选项。但首选方法是使用预加载脚本:electronjs.org/docs/latest/tutorial/tutorial-preloadwebPreferences: { nodeIntegration: true }

答: 暂无答案