我在 venv 中的 python 3.12.1 (Windows 11) 中使用 eel。我试图实现的是,使用 vlc,播放歌曲,并有一个函数在调用时返回当前播放时间。
我公开了一个定义的函数,该函数返回歌曲加载并播放后从 vlc 获取的当前时间。
当我使用 javascript 调用该函数时,问题就出现了。
这是代码
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()
在 JavaScript 文件中
// 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);
当我运行 python 文件(启动 eel 并导入此 vlc 媒体播放文件以启动歌曲时,我收到此错误:
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
顺便说一句,这是我的软件包和使用的版本
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
要调用 eel 函数并对结果调用回调,语法应为:
eel.foreign_function(args_of_foreign_function)(callback);
也就是说:调用 eel 修饰的函数会返回一个可调用对象,可以使用回调函数作为参数来调用它。
这对于 Python 和 Javascript 来说是一样的,但是分号在 JS 中当然是可选的。
参考:Eel 关于回调的文档。
您的原始代码相当于:
eel.foreign_function(callback);
这给出了您看到的错误,因为
callback
被提供给 Python 函数本身,而不是提供给 eel 包装的 Python 函数返回的对象。
正如您在评论中发现并提到的,您的案例中的正确调用是:
eel.get_song_current_time()( result => {console.log(result);} );