Ciaran Walker Ciaran Walker - 1 year ago 212
Python Question

Python Error: "global name server_loop() is not defined"

I have been following along the "black hat python" book and when I typed in this particular code I got the error "global name server_loop() is not defined". Here is the statement BEFORE the main() function having the error:

if listen:

and here is the server_loop() function IN the main() function:

def server_loop():
global target

# if no target is defined, we listen on all interfaces
if (not len(target)):
target = ""

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((target, port))

while True:
client_socket, addr = server.accept()

# spin off a thread to handle our new client
client_thread = threading.Thread(target=client_handler, args=(client_socket,))


Answer Source

I hope I understand the question correctly.

I can reproduce your case easily:


def something():

I get

Traceback (most recent call last):
  File "<string>", line 420, in run_nodebug
  File "<module1>", line 1, in <module>
NameError: name 'something' is not defined

If I call something after having defined it it works.

You have to define functions before using them.

I suppose that your book just gave the information in the inverted order (top => down, from global/main to implementation/function) expecting that you knew that as a lot of languages, python requires function definition before function call. Personally I prefer single-block examples that you can type (or copy/paste) without thinking and it works right away.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download