繁体   English   中英

如何在我的 python 代码中集成 python 脚本

[英]How to integrate python scripting in my python code

我正在编写 Python 代码(基于 PyQt5 信号和插槽)。 我需要使我的代码“可编写脚本”。 可编写脚本是指用户可以自己在用户定义的 python 脚本中利用内部对象来开发/自动化某些功能,..等。 但我不知道如何清楚地实施它。

我尝试通过以下方式在 python 中使用(exec)function:

用户定义.py

def script_entry(main_object_in_my_code):
    # Connecting signal from main_object_in_my_code (inherited from QObject) to other functions in this 
    # file. example:
    main_object_in_my_code.event_1.connect(function_1)

@QtCore.pyqtSlot(str)
def function_1 (args):
    #do user-defined logic using those args.

然后在我的脚本中,当用户想要执行它时,他输入(例如)

源用户-def.py

主脚本读取脚本并使用 exec 如下:

with open(script_path) as f:
    script = f.read()

exec(script, globals())

问题是触发了事件,但未执行 function function_1。

我确信这不是正确的方法。 那么,如何使用用户定义的脚本实现我的代码(可编写脚本)?

我建议创建一个 class 并从中扩展,让“用户”在需要时调用函数。

如果您没有与 class inheritance 联系,请查看本教程

source_def.py

class Main:
    def __init__(self):
        super(Main, self).__init__()

    def script_entry(self, main_object_in_my_code):
        main_object_in_my_code.event_1.connect( function_1 )

    @QtCore.pyqtSlot(str)
    def function_1( self, args ):

        #this checks if the function is set
        invert_op = getattr(self, "user_function", None)
        if callable(user_function):
            eval('self.user_function( args )')

用户定义.py

from source_def import Main

class UserClass( Main ):

    def __init__(self):
        super(UserClass, self).__init__()

    def user_function(self , args ):
        print( args )

尝试这个

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM