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

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

    A way like Reflection in Java? If so, Python has a module named imp to provide it.

    foo.py

    def foo():
      return "return from function foo in file foo.py"
    

    some code anywhere

    modes = imp.get_suffixes() #got modes Explained in link below
    mode = modes[-2] # because I want load a py file
    with open("foo.py") as file:
      m = imp.load_module("name", file, "foo.py", mode)
    print(m.foo())
    

    above mode = modes[-2] because my imp.get_suffixes() is:

    >>> imp.get_suffixes()
    [('.cpython-32m.so', 'rb', 3), ('module.cpython-32m.so', 'rb', 3), ('.abi3.so', 'rb', 3), ('module.abi3.so', 'rb', 3), ('.so', 'rb', 3), ('module.so', 'rb', 3), ('.py', 'U', 1), ('.pyc', 'rb', 2)]
    

    here is my output:

    Python 3.2.1 (default, Aug 11 2011, 01:27:29) 
    [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import imp
    >>> with open("foo.py") as file:
    ...   m = imp.load_module("foo", file, "foo.py", ('.py', 'U', 1))
    ... 
    >>> m.foo()
    'return from function foo in file foo.py'
    

    Check it here: http://docs.python.org/py3k/library/imp.html Both python 2.7 and python 3 works:

    Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05) 
    [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import imp
    >>> imp.get_suffixes()
    [('.so', 'rb', 3), ('module.so', 'rb', 3), ('.py', 'U', 1), ('.pyc', 'rb', 2)]
    >>> with open("foo.py") as file:
    ...   m = imp.load_module("foo", file, "foo.py", ('.py', 'U', 1))
    ... 
    >>> m.foo()
    'return from function foo in file foo.py'
    

提交回复
热议问题