简体   繁体   中英

Python not importing files as modules correctly

I am trying to get Python code to work on a web browser using the CGI module, as well as some other file modules that I am trying to import into the main program.

My initial program, which works as required, is the following:

#!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()

In the same folder as this program, I have a Python file called "_serverTestModules" containing:

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

If I then add:

import _serverTestModules

to the original file, both of which are in the same directory, and attempt to access the function from the original code, I get this error:

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

So basically my test program works, but as soon as I try to import functions from other files which are in the same directory (something which I need for my main project), the code fails. Is this a problem with the computer system or the network? Every other answer I have seen on Stack Overflow has either had no answer or an incorrect answer, so any help is much appreciated.

你需要用这个

from _serverTestModules import _serverTestFunction

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM