Python没有正确地将文件作为模块导入

2024-09-28 23:00:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让Python代码在web浏览器上使用CGI模块,以及我试图导入到主程序中的一些其他文件模块

我的初始计划(按要求运行)如下所示:

#!C:\Users\Student\AppData\Local\Programs\Python\Python37-32\python.exe

import cgi

def htmlTop():
    print("Content-type: text/html")
    print()
    print("""<!DOCTYPE html>
        <html lang="en">
            <head>
                    <meta charset="utf-8"/>
                    <title>My Server Side Test</title>
            </head>
            <body>""")

def htmlTail():
    print("""</body>
    </html>""")

if __name__ == "__main__":
    try:
        htmlTop()
        print("Hello World")
        htmlTail()
    except:
        cgi.print_exception()

在与此程序相同的文件夹中,我有一个名为“\u serverTestModules”的Python文件,其中包含:

def _serverTestFunction():
print("The file has been imported successfully")

如果我再加上:

import _serverTestModules

对于原始文件(两者都在同一目录中),并尝试从原始代码访问函数,我得到以下错误:

Traceback (most recent call last):
  File "C:/xampp/htdocs/inventorysystem/_serverTest.py", line 26, in <module>
    _serverTestFunction()
NameError: name '_serverTestFunction' is not defined

因此,基本上我的测试程序可以工作,但只要我尝试从同一目录中的其他文件(我的主项目需要的东西)导入函数,代码就会失败。这是计算机系统还是网络的问题?我在Stack Overflow上看到的所有其他答案要么没有答案,要么答案不正确,因此非常感谢您的帮助


Tags: 模块文件答案代码importtitledefhtml