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
script.py
node_script.js
Child Process Module:
Use the
child_process
module whichNode.js
provides to spawn child processes and runPython
code.Code:
In Python Script parse the arguments:
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:
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.