简体   繁体   English

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

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

I am writing Python code (based on PyQt5 signals and slots).我正在编写 Python 代码(基于 PyQt5 信号和插槽)。 I need to make my code "Scriptable".我需要使我的代码“可编写脚本”。 By scriptable I mean the user can utilize the internal objects himself in a user-defined python script to develop/automate some functions,..etc.可编写脚本是指用户可以自己在用户定义的 python 脚本中利用内部对象来开发/自动化某些功能,..等。 But I have no idea of how to implement it clearly.但我不知道如何清楚地实施它。

I have tried using (exec) function in python in the following way:我尝试通过以下方式在 python 中使用(exec)function:

user-def.py用户定义.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.

then in my script when user want to execute it, he inputs (as example)然后在我的脚本中,当用户想要执行它时,他输入(例如)

source user-def.py源用户-def.py

the main script reads the script and uses exec as the following:主脚本读取脚本并使用 exec 如下:

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

exec(script, globals())

the problem is that events are triggered but function function_1 is not executed.问题是触发了事件,但未执行 function function_1。

I am sure this is not the right way to do this.我确信这不是正确的方法。 So, How can I implement my code to be (scriptable) using user defined scripts?那么,如何使用用户定义的脚本实现我的代码(可编写脚本)?

I would recomend to create a class and extend from it, let the 'user' call the functions when s/he needs.我建议创建一个 class 并从中扩展,让“用户”在需要时调用函数。

If you are not in touch with class inheritance check this tutorial如果您没有与 class inheritance 联系,请查看本教程

source_def.py 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 )')

user_def.py用户定义.py

from source_def import Main

class UserClass( Main ):

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

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

Try this尝试这个

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

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