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

前端 未结 5 1923
故里飘歌
故里飘歌 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:33

    You can use execfile:

    execfile("path/example.py")
    
    # example.py
    # def example_func():
    #     return "Test"
    #
    
    print example_func()
    # >Test
    

    EDIT:

    In case you want to execute some unsecure code, you can try to sandbox it this way, although it is probably not very safe anyway:

    def execfile_sandbox(filename):
        from copy import copy
        loc = globals()
        bi  = loc["__builtins__"]
        if not isinstance(bi, dict): bi = bi.__dict__ 
    
        bi = copy(bi)        
        # no files
        del bi["file"]    
        # and definitely, no import
        del bi["__import__"]
        # you can delete other builtin functions you want to deny access to
    
        new_locals = dict()
        new_locals["__builtins__"] = bi
        execfile(filename, new_locals, new_locals)
    

    Usage:

    try:
        execfile_sandbox("path/example.py")
    except:
        # handle exception and errors here (like import error)
        pass
    

提交回复
热议问题