Python: How to pass arguments to the __code__ of a function?

前端 未结 6 449
别那么骄傲
别那么骄傲 2020-12-02 20:55

The following works:

def spam():
    print \"spam\"
exec(spam.__code__)

spam

But what if spam

6条回答
  •  眼角桃花
    2020-12-02 21:41

    Can you change the function to not take any arguments? The variables is then looked up from the locals/globals where you can supply into exec:

    >>> def spam():
    ...   print "spam and", eggs
    ... 
    >>> exec(spam.__code__, {'eggs':'pasta'})
    spam and pasta
    

    (Why not just send the whole function as a string? Pickle "def spam(eggs): print 'spam and', eggs", and exec the string (after verification) on the other side.)

提交回复
热议问题