Python 包含多个 python 文件的程序

Python program which contains several python files

我想编写一个python程序,例如main.py,其中包含两个或多个python程序(test1.py,test2.py.. etc,.) 它们被放置在这些程序的其他一些目录中,所有这些程序都有自己的带有参数的方法(test1.py,test2.py..etc,.)。我尝试了一些但案例失败,其中包含程序中的参数。是否有任何简单的方法可以在一个主要 python 程序中访问多个程序?

当然可以。您可以使用 import 加载其他 python 个文件:

# Use file1.py, file2.py
import file1
from file2 import func2

file1.func1()
func2()

如果你的其他文件是程序,而不是简单的变量,class和函数,你可以避免执行此程序中的代码,如下所示:

# file1.py(old)

def func1():
   ...

func1()  # Execute func1 when this file is loaded.
# file1.py(new)

def func1():
   ...

if __name__=='__main__':
   func1()  # Execute func1 when this file is loaded.

如果这是第一个加载的文件,if __name__=='__main__' 块中的代码只有 运行。

# Use file1.py, file2.py
import file1
from file2 import func2

file1.func1()
func2()

如果您想将这些文件组织到一个目录中,则必须创建一个 'module'。这只需要您在目录中放置一个空 __init__.py

 + test.py
 + mymodule/
    + file1.py
    + file2.py
# Test.py. Use mymodule/file1.py, mymodule/file2.py
import mymodule.file1
from mymodule.file2 import func2

file1.func1()
func2()

如果 运行 时 mymodule 在当前目录中,这将起作用。 (即你 运行 python test.py 而不是 python a/b/c/test.py.

详细答案见http://docs.python.org/3/tutorial/modules.html