Running Python code contained in a string

前端 未结 4 1517
终归单人心
终归单人心 2020-12-03 12:32

I\'m writing a game engine using pygame and box2d, and in the character builder, I want to be able to write the code that will be executed on keydown events.

My plan

4条回答
  •  遥遥无期
    2020-12-03 12:47

    As others have pointed out, you can load the text into a string and use exec "codestring". If contained in a file already, using execfile will avoid having to load it.

    One performance note: You should avoid execing the code multiple times, as parsing and compiling the python source is a slow process. ie. don't have:

    def keydown(self, key):
        exec user_code
    

    You can improve this a little by compiling the source into a code object (with compile() and exec that, or better, by constructing a function that you keep around, and only build once. Either require the user to write "def my_handler(args...)", or prepend it yourself, and do something like:

    user_source = "def user_func(args):\n" + '\n'.join("    "+line for line in user_source.splitlines())
    
    d={}
    exec user_source in d
    user_func = d['user_func']
    

    Then later:

    if key == K_a:
       user_func(args)
    

提交回复
热议问题