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

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

    I am not sure what is your purpose, but I suppose that you have function in one program and you do want that function run in another program. You can "marshal" function from first to second.

    Example, first program:

    # first program
    def your_func():
        return "your function"
    
    import marshal
    marshal.dump(your_func.func_code, file("path/function.bin","w"))
    

    Second program:

    # Second program
    
    import marshal, types
    code = marshal.load(file("path/function.bin"))
    your_func = types.FunctionType(code, globals(), "your_func")
    
    print your_func()
    # >your function
    

提交回复
热议问题