Skip to content

Navigation Menu

Sign in
Sign up

Run specific function without running everything #466

Answered by wiwichips
novitae asked this question in Q&A
Discussion options

Hey, I was wondering if there was a way to run one function, but not the whole js script. I've only seen examples where only one function is ran. Would there be a way to do the following ?

function hello() {return "hello";};
function world() {return "world";};
>>> evaluated.hello()
"hello"
>>> evalutated.world()
"world"
You must be logged in to vote

Hi @novitae - Here's one way to do it using globalThis after evaluating the functions.

import pythonmonkey
pythonmonkey.eval("""
function hello() {return "hello";};
function world() {return "world";};
""")
print(pythonmonkey.globalThis.hello())
print(pythonmonkey.globalThis.world())

which outputs

hello
world

A cleaner approach might be to use separate files and then use CommonJS to require the JavaScript file / module for use in your Python program

myjsfunctions.js

function hello() {return "hello";};
function world() {return "world";};
exports.hello = hello;
exports.world = world;

my_python_file.py

import pythonmonkey
evaluated = pythonmonkey.require('./myjsfunctions');
print(evaluated

Replies: 1 comment

Comment options

Hi @novitae - Here's one way to do it using globalThis after evaluating the functions.

import pythonmonkey
pythonmonkey.eval("""
function hello() {return "hello";};
function world() {return "world";};
""")
print(pythonmonkey.globalThis.hello())
print(pythonmonkey.globalThis.world())

which outputs

hello
world

A cleaner approach might be to use separate files and then use CommonJS to require the JavaScript file / module for use in your Python program

myjsfunctions.js

function hello() {return "hello";};
function world() {return "world";};
exports.hello = hello;
exports.world = world;

my_python_file.py

import pythonmonkey
evaluated = pythonmonkey.require('./myjsfunctions');
print(evaluated.hello())
print(evaluated.world())

Output

$ python3 my_python_file.py 
hello
world

Let me know if that answers your question!

You must be logged in to vote
0 replies
Answer selected by novitae
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /