How can I call my Python function in my javaScript file?

300 views Asked by At

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!

1

There are 1 answers

0
Node Developer On

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('python3', [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}`);
});