javascriptpythoncallbackargumentseel

Python is raising a Type error upon calling its function with a callback functionn using javascript (in eel)


Im using eel in python 3.12.1 (Windows 11) inside a venv. What Im trying to implement is, using vlc, play a song, and have a function that returns the currently playing time when called.

I exposed a defined function that returns the current time obtained from vlc after the song is loaded and played.

The problem comes when I call the function using javascript.

Here's the code

import vlc
import eel

audio_file # audio file path. for eg. D:\\TheGreatMusicFolder\VeryStupidSong.mp3

song = vlc.MediaPlayer(audio_file)

song.play() # the song plays

@eel.expose
def get_song_current_time():
    return song.get_time()

in the javascript file

// Code that handles the icon changing of play/pause button
// eel.js is imported in the html file as instructed in eel's documentaion (in github)
const currentTime = document.getElementById("current_time_display");

let currentTimeValue = 0;

eel.get_song_current_time((result) => {
    currentTimeValue = result;
});

console.log(currentTimeValue);

for which when i run the python file (that initiates the eel and imports this vlc media playing file to start the song, i get this error:

Traceback (most recent call last):
  File "(THE FOLDER IN WHICH THIS PROJECT RESIDES)\env\Lib\site-packages\eel\__init__.py", line 318, in _process_message
    return_val = _exposed_functions[message['name']](*message['args'])
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: get_song_current_time() takes 0 positional arguments but 1 was given

BTW here's my packages and ther versions used

bottle==0.12.25
bottle-websocket==0.2.9
cffi==1.16.0
Eel==0.16.0
future==0.18.3
gevent==23.9.1
gevent-websocket==0.10.1
greenlet==3.0.3
pycparser==2.21
pyparsing==3.1.1
python-vlc==3.0.20123
setuptools==69.0.3
whichcraft==0.6.1
zope.event==5.0
zope.interface==6.1

Solution

  • To call the eel function and invoke a callback on the result, the syntax should be:

    eel.foreign_function(args_of_foreign_function)(callback);
    

    That's to say: calling the eel-decorated function returns a callable, which can be called with a callback function as argument.

    This is the same for Python and Javascript, but of course the semicolon is optional in Python.

    Reference: Eel documentation on callbacks.

    Your original code did the equivalent of:

    eel.foreign_function(callback);
    

    That gave the error you saw, because callback was being supplied to the Python function itself, rather than to the object returned by the eel-wrapped Python function.

    As you found and mentioned in the comments, the correct call in your case is:

    eel.get_song_current_time()( result => {console.log(result);} );