简体   繁体   中英

How to integrate python scripting in my python code

I am writing Python code (based on PyQt5 signals and slots). 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. But I have no idea of how to implement it clearly.

I have tried using (exec) function in python in the following way:

user-def.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

the main script reads the script and uses exec as the following:

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.

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.

If you are not in touch with class inheritance check this tutorial

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

from source_def import Main

class UserClass( Main ):

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

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

Try this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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