3

我有多个 python 文件,每个文件都有不同的类和方法。我想使用我在所有文件之外单独拥有的主要功能来执行所有这些文件。

例如:

我有三个文件,分别是 one.py、two.py、three.py

我在其中任何一个中都没有 main 方法,但是当我执行它们时,我希望它们通过我单独拥有的 main 函数。这可能吗,怎么做?

谢谢。

4

4 回答 4

7

你的意思是你想导入它们?

import one
import two
import three

result = one.func()
instance = two.YourClass()
something = three.func()

请注意,python 中没有“主要方法”(也许您一直在使用 JAVA?)。当您说 时python thisfile.py,python 会执行“thisfile.py”中的所有代码。我们使用的一个巧妙的小技巧是每个“模块”都有一个属性“名称”。直接调用的脚本(例如thisfile.py)被分配了名称"__main__"。这使您可以将模块的一部分作为脚本分开,另一部分打算在其他地方重用。一个常见的用例是测试:

#file: thisfile.py
def func():
   return 1,2,3

if __name__ == "__main__":
   if func() != (1,2,3):
      print "Error with func"
   else:
      print "func checks out OK"

现在,如果我将其作为 运行python thisfile.py,它将打印func checks out OK,但如果我将其导入另一个文件,例如:

#anotherfile.py
import thisfile

然后我通过运行该文件python anotherfile.py,不会打印任何内容。

于 2012-09-26T14:02:50.167 回答
4

将它们用作模块并将它们导入到包含 main 的脚本中。

import one
import two
import three

if __name__ == '__main__':
    one.foo()
    two.bar()
    three.baz()
于 2012-09-26T14:04:22.930 回答
2

创建一个新文件来导入这些文件并运行该文件。

于 2012-09-26T14:03:50.973 回答
1

正如之前的答案所暗示的,如果您只需要重新使用该功能,请执行导入。

但是,如果您事先不知道文件名,则需要使用稍微不同的导入构造。对于one.py位于同一目录中的文件,请使用:

one.py的内容:

print "test"
def print_a():
    print "aa"

您的主文件:

if __name__ == "__main__":
    imp = __import__("one")
    print dir(imp)

打印出测试并提供有关导入文件中包含的方法的信息。

于 2012-09-26T14:07:09.103 回答