无法从导入的文件中运行代码

时间:2016-12-07 20:17:09

标签: python import

如何运行我在另一个文件中创建的函数?我知道有很多问题要问这个,但我的代码很简单,我不知道它是如何工作的。

在一个名为Testfile的文件中,我有

def greeting():
    print("Hello")

在另一个我有

import Testfile

greeting()

但是当我运行代码时,我得到了错误 "姓名'问候'未定义"

2 个答案:

答案 0 :(得分:0)

import Testfile    
Testfile.greeting()

from Testfile import greeting
greeting()

您必须使用.指定函数来自哪个模块,或者在导入时告诉它。

答案 1 :(得分:0)

您必须在包含该功能的模块后调用该功能:

po::options_description opts("SendFile Options");

    opts.add_options()("help,h", "Print this help message")
        ("other,o","This is the other");

请注意,此方法更好,因为这可能会导致命名空间冲突并阻止程序的可伸缩性。

请关注PEP 8, section module names