如何在python中调用Javascript函数?

如何在python中调用Javascript函数?,javascript,python-3.x,electron,Javascript,Python 3.x,Electron,我正在尝试用电子和深度强化学习制作一个蛇游戏。我用python做的强化学习和用Javascript做的游戏。现在我如何在python中调用这样的函数 makeSomeThing(x) { } 或 嗯,我不知道这是否是您期望的答案,但我将创建一个独立的python服务,公开一些API 在electron中创建一个客户端,并使用python API从python服务发送数据和获取处理过的信息 您不能从python调用Javascript API。无论如何,你需要中间的东西。 请将python脚本

我正在尝试用电子和深度强化学习制作一个蛇游戏。我用python做的强化学习和用Javascript做的游戏。现在我如何在python中调用这样的函数

makeSomeThing(x) {

}


嗯,我不知道这是否是您期望的答案,但我将创建一个独立的python服务,公开一些API

在electron中创建一个客户端,并使用python API从python服务发送数据和获取处理过的信息

您不能从python调用Javascript API。无论如何,你需要中间的东西。
  • 请将python脚本构建为可执行的二进制文件。您可以使用将python脚本打包为独立的可执行文件

  • 然后你可以像这样在你的Electron项目中生成这个二进制文件

    import { spawn } from 'child_process';
    // in my case I'm storing the file at bin directory at the root path of the application
    // You can change this whatever you want
    
    const pythonPath = const basicURL = process.env.NODE_ENV === 'development'
    ? path.join(__dirname, './bin/xxxx')
    : path.join(process.resourcesPath, 'bin', 'xxxx');
    
    const params = ['arg1', 'arg2'];  // params that your python scripts need.
    const pythonChildProcess = spawn(pythonPath, params);
      pythonChildProcess.stdout.on('data', data => {
        console.log(`stdout: ${data}`);
    
        // Here is where the output goes
      });
      pythonChildProcess.stderr.on('data', data => {
        console.log(`tderr: ${data}`);
    
        // Here is where the error output goes
      });
      pythonChildProcess.on('close', code => {
        console.log(`closing code: ${code}`);
        // Here you can get the exit code of the script
      });
    

  • 你用什么框架来连接Python和Electron?没有,我不知道如何组合它们。使用
    pyexecjs
    module调用js文件中的函数。实际上我只需要“发送”js和py之间的数据,我认为这是在文件中存储数据而不是读取数据时最简单的方法。谢谢tpikachu,但我想用python调用Javascript函数。@GianLaager不是一种正常的方法。但我想当你们要在Electron应用程序上运行python脚本时
    import { spawn } from 'child_process';
    // in my case I'm storing the file at bin directory at the root path of the application
    // You can change this whatever you want
    
    const pythonPath = const basicURL = process.env.NODE_ENV === 'development'
    ? path.join(__dirname, './bin/xxxx')
    : path.join(process.resourcesPath, 'bin', 'xxxx');
    
    const params = ['arg1', 'arg2'];  // params that your python scripts need.
    const pythonChildProcess = spawn(pythonPath, params);
      pythonChildProcess.stdout.on('data', data => {
        console.log(`stdout: ${data}`);
    
        // Here is where the output goes
      });
      pythonChildProcess.stderr.on('data', data => {
        console.log(`tderr: ${data}`);
    
        // Here is where the error output goes
      });
      pythonChildProcess.on('close', code => {
        console.log(`closing code: ${code}`);
        // Here you can get the exit code of the script
      });