How to call a function stored in another file from a Python program?

前端 未结 5 1918
故里飘歌
故里飘歌 2021-01-07 02:44

If I have a text file that contains a python function definition, how can I make the function call from another Python program. Ps: The function will be defined in the Pytho

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-07 03:23

    compile() and eval() can do the trick:

    >>> code = compile('def foo(a): return a*2', '', 'exec')
    >>> eval(code)
    >>> foo
    52: 
    >>> foo(12)
    53: 24
    

    or with file:

    with open(filename) as source:
        eval(compile(source.read(), filename, 'exec'))
    

提交回复
热议问题