简体   繁体   中英

Python 3 module import error

I have created a python 3.4 file and trying to import some of the variables into another python script. Both of the scripts are in the same folder but I keep getting an error.

I can use the import and it works fine. However when I try to import variables from the script using from ServerConfiguration import port, ip I get an error saying NameError: name 'ServerConfiguration' is not defined

ServerConfiguration module:

import socket
import sys
import os

serverIP = None

def serverSocket():
    PORT = 8884 # Port the server is listening on

ServerEst = input('Has a server been established')
if ServerEst == 'yes':
    ServerIP = input ('Enter the servers IP address')
    socks = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    socks.bind((ServerIP, PORT))
    print('Connection  Established at ' + serverIP)
else:
    CreateServer = input('Would you like to create a server')
    if CreateServer == 'yes':
        ServerIP = input('What is you LAN IP? Please remeber if reomte user are allowed to connect port forward port "8884" ')
        socks = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        socks.bind((ServerIP, PORT))
        print('Connection  Established to ' + ServerIP)
    else:
        print ('Defaulting to default')
        ServerIP = 'localhost'
        socks = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        socks.bind((ServerIP, PORT))
        print('Connection  Established to ' + ServerIP)

UserModule:

    from ServerConfiguration import serverSocket, serverIP 
    import socket
    import sys
    import os

    def sendMessage():
        sockc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        while True:
              MESSAGE = input('Type the message to send ')
              sockc.sendto((MESSAGE.encode, "utf-8"), (serverIP, PORT))
              print(MESSAGE)


    ServerConfiguration.serverSocket()
    sendMessage()

If you use

from ServerConfiguration import serverSocket, serverIP 

you should write just

serverSocket()

without ServerConfiguration.

Another way:

import ServerConfiguration
...
ServerConfiguration.serverSocket()

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