How do I get the return value when using Python exec on the code object of a function?

前端 未结 5 1813
再見小時候
再見小時候 2020-12-06 04:04

For testing purposes I want to directly execute a function defined inside of another function.

I can get to the code object of the child function, through the code (

5条回答
  •  旧巷少年郎
    2020-12-06 04:54

    While this is the ugliest beast ever seen by mankind, this is how you can do it by using a global variable inside your exec call:

    def my_exec(code):
        exec('global i; i = %s' % code)
        global i
        return i
    

    This is misusing global variables to get your data across the border.

    >>> my_exec('1 + 2')
    3
    

    Needless to say that you should never allow any user inputs for the input of this function in there, as it poses an extreme security risk.

提交回复
热议问题