如何包括外部Python代码以在其他文件中使用?

问题:如何包括外部Python代码以在其他文件中使用?

如果文件中有一组方法,是否可以将这些文件包含在另一个文件中,但不带任何前缀(即文件前缀)调用它们?

所以,如果我有:

[Math.py]
def Calculate ( num )

我怎么这样称呼它:

[Tool.py]
using Math.py

for i in range ( 5 ) :
    Calculate ( i )

If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)?

So if I have:

[Math.py]
def Calculate ( num )

How do I call it like this:

[Tool.py]
using Math.py

for i in range ( 5 ) :
    Calculate ( i )

回答 0

您将需要将其他文件作为模块导入,如下所示:

import Math

如果您不想在Calculate函数名称前加上模块名称,请执行以下操作:

from Math import Calculate

如果要导入模块的所有成员,请执行以下操作:

from Math import *

编辑: 这是Dive Into Python 的精彩一章,在该主题上有更深入的介绍。

You will need to import the other file as a module like this:

import Math

If you don’t want to prefix your Calculate function with the module name then do this:

from Math import Calculate

If you want to import all members of a module then do this:

from Math import *

Edit: Here is a good chapter from Dive Into Python that goes a bit more in depth on this topic.


回答 1

只需编写“ include”命令:

import os

def include(filename):
    if os.path.exists(filename): 
        execfile(filename)


include('myfile.py')

@Deleet:

@bfieck的评论是正确的,对于python 2和3的兼容性,您需要:

Python 2和3:替代方法1

from past.builtins import execfile

execfile('myfile.py')

Python 2和3:替代2

exec(compile(open('myfile.py').read()))

Just write the “include” command :

import os

def include(filename):
    if os.path.exists(filename): 
        execfile(filename)


include('myfile.py')

@Deleet :

@bfieck remark is correct, for python 2 and 3 compatibility, you need either :

Python 2 and 3: alternative 1

from past.builtins import execfile

execfile('myfile.py')

Python 2 and 3: alternative 2

exec(compile(open('myfile.py').read()))

回答 2

如果您使用:

import Math

那么这将允许您使用Math的函数,但是您必须执行Math.Calculate,因此显然这是您不想要的。

如果要导入模块的功能而不必加上前缀,则必须显式命名它们,例如:

from Math import Calculate, Add, Subtract

现在,您可以仅按其名称引用“计算”​​,“添加”和“减去”。如果要从Math导入ALL函数,请执行以下操作:

from Math import *

但是,对不确定内容的模块执行此操作时应非常小心。如果导入两个包含相同功能名称定义的模块,则一个功能将覆盖另一个功能,而没有一个则更明智。

If you use:

import Math

then that will allow you to use Math’s functions, but you must do Math.Calculate, so that is obviously what you don’t want.

If you want to import a module’s functions without having to prefix them, you must explicitly name them, like:

from Math import Calculate, Add, Subtract

Now, you can reference Calculate, Add, and Subtract just by their names. If you wanted to import ALL functions from Math, do:

from Math import *

However, you should be very careful when doing this with modules whose contents you are unsure of. If you import two modules who contain definitions for the same function name, one function will overwrite the other, with you none the wiser.


回答 3

我发现python inspect模块非常有用

例如,使用teststuff.py

import inspect

def dostuff():
    return __name__

DOSTUFF_SOURCE = inspect.getsource(dostuff)

if __name__ == "__main__":

    dostuff()

并从另一个脚本或python控制台

import teststuff

exec(DOSTUFF_SOURCE)

dostuff()

现在dostuff应该在本地范围内,并且dostuff()将返回控制台或脚本_ name _,而执行test.dostuff()将返回python模块名称。

I’ve found the python inspect module to be very useful

For example with teststuff.py

import inspect

def dostuff():
    return __name__

DOSTUFF_SOURCE = inspect.getsource(dostuff)

if __name__ == "__main__":

    dostuff()

And from the another script or the python console

import teststuff

exec(DOSTUFF_SOURCE)

dostuff()

And now dostuff should be in the local scope and dostuff() will return the console or scripts _name_ whereas executing test.dostuff() will return the python modules name.