skip to Main Content

I want to use my Python function in JavaScript. Obviously, my code is more complicated than demonstrated below, but this is the smallest base on which I was able to replicate the problem:

main.mjs

dbutils.notebook.run("./aPythonFile.py", 5, {"parameter1": "helloWorld"})

aPythonFile.py:

def my_python_function(parameter1):
    print(parameter1)

Error message:

ReferenceError: dbutils is not defined
at file:///c:/Users/q612386/Dev/SkillUp/SUPAC23-53/Python%20+%20JavaScript%20(ohne%20Listener%20oder%20API)/scripts/tempCodeRunnerFile.js:1:1
at ModuleJob.run (node:internal/modules/esm/module_job:194:25)

Changing .mjs to .js did not fix the problem.

I am sure it is just a weird import error but I can’t seem to find it. Any other simple solution to call a python function in JavaScript is very welcome, too (except for Flask or django).

Thank you!

3

Answers


  1. script.py

    import sys
    
    # Receive arguments from Node.js
    arg_from_node = sys.argv[1]
    print("Argument received from Node.js:", arg_from_node)
    
    # Your Python code here...
    

    node_script.js

    const { spawn } = require('child_process');
    
    // Path to your Python script
    const pythonScript = 'path/to/script.py';
    
    // Dynamic value from Node.js
    const dynamicValue = 'Hello from Node.js';
    
    // Spawn a child process
    const pythonProcess = spawn('python', [pythonScript, dynamicValue]);
    
    // Listen for data from the Python script
    pythonProcess.stdout.on('data', (data) => {
      console.log(`Python Output: ${data}`);
    });
    
    // Listen for any errors from the Python script
    pythonProcess.stderr.on('data', (data) => {
      console.error(`Error from Python: ${data}`);
    });
    
    // Listen for the process to exit
    pythonProcess.on('close', (code) => {
      console.log(`Python process exited with code ${code}`);
    });
    
    Login or Signup to reply.
  2. Child Process Module:
    Use the child_process module which Node.js provides to spawn child processes and run Python code.

    Code:

    const { spawn } = require('child_process');
    
    const pythonProcess = spawn('python', ['./aPythonFile.py', 'helloWorld']);
    
    pythonProcess.stdout.on('data', (data) => {
      console.log(`stdout: ${data}`);
    });
    
    pythonProcess.stderr.on('data', (data) => {
      console.error(`stderr: ${data}`);
    });
    
    pythonProcess.on('close', (code) => {
      console.log(`child process exited with code ${code}`);
    });
    

    In Python Script parse the arguments:

    import sys
    
    def my_python_function(parameter1):
        print(parameter1)
    
    if __name__ == "__main__":
        my_python_function(sys.argv[1])
    
    Login or Signup to reply.
  3. Node.js allows you to spawn child processes to run external commands. You can use this to execute Python scripts. To run Python code from JavaScript outside of a framework like Flask or Django, you can consider this method:

    You can do it this way:

    const { spawn } = require('child_process');
    
    const pythonProcess = spawn('python', ['./aPythonFile.py', 'helloWorld']);
    
    pythonProcess.stdout.on('data', (data) => {
      console.log(`stdout: ${data}`);
    });
    
    pythonProcess.stderr.on('data', (data) => {
      console.error(`stderr: ${data}`);
    });
    
    pythonProcess.on('close', (code) => {
      console.log(`child process exited with code ${code}`);
    });
    

    If you prefer not to use Flask or Django, you can still create a simple HTTP server in Python that listens for requests and executes your Python function. You can then call this server from your JavaScript code using HTTP requests.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search