在 Python 应用程序中编写脚本 [英] Scripting inside a Python application
问题描述
我想在我的一个应用程序中包含 Python 脚本,该应用程序是用 Python 本身编写的.
I'd like to include Python scripting in one of my applications, that is written in Python itself.
我的应用程序必须能够调用外部 Python 函数(由用户编写)作为回调.必须对代码执行进行一些控制;例如,如果用户提供的代码有语法错误,应用程序必须发出信号.
My application must be able to call external Python functions (written by the user) as callbacks. There must be some control on code execution; for example, if the user provided code with syntax errors, the application must signal that.
这样做的最佳方法是什么?
谢谢.
What is the best way to do this?
Thanks.
编辑:问题不清楚.我需要一种类似于 VBA 事件的机制,其中有一个声明"部分(您可以在其中定义全局变量)和事件,以及在特定点触发的脚本代码.
edit: question was unclear. I need a mechanism similar to events of VBA, where there is a "declarations" section (where you define global variables) and events, with scripted code, that fire at specific points.
推荐答案
使用 __import__
导入用户提供的文件.此函数将返回一个模块.使用它从导入的文件中调用函数.
Use __import__
to import the files provided by the user. This function will return a module. Use that to call the functions from the imported file.
在 __import__
和实际调用中使用 try..except
来捕获错误.
Use try..except
both on __import__
and on the actual call to catch errors.
示例:
m = None
try:
m = __import__("external_module")
except:
# invalid module - show error
if m:
try:
m.user_defined_func()
except:
# some error - display it
这篇关于在 Python 应用程序中编写脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!