user2381309 user2381309 - 5 months ago 28x
Python Question

Python Thread Not Starting

Mashing code from a few different sources I am trying to make a python chat client. I can connect to the server but I want to use two threads so I can send and recieve messages at the same time. I am new to python and cannot get my threads to work. My python version is 2.7.5


import sys
import socket
import time
import threading

# Define a function for the thread
def sendChat( socket, name):
userInput = ""
while userInput != "exit":
userInput = raw_input("What do you want to say")
userInput = (userInput+'\r\n')

print "Hello, Python!"

userName = raw_input("What would you like your user name to be:")
print (userName + " welcome to chatclient, connecting to server now...")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
host = socket.gethostname() # Get local machine name
port = 4444
s.connect((host, port))
print "... connected to server!"
thread.start_new_thread( sendChat, (s, "sendChat" ) )
print "Error: unable to start thread"


Here is what I get when I run it:

Ryans-MacBook-Pro:network ryan$ python
Hello, Python!
What would you like your user name to be:ryan
ryan welcome to chatclient, connecting to server now...
... connected to server!
Error: unable to start thread

I have seen that the main thread can end before the new one so I tried add the sleep at the end but that didn't work.


Well, with the code exactly as given, your catch-all try/except is hiding the obvious cause. If I remove the try/except, I get:

Traceback (most recent call last):
  File "", line 26, in <module>
    thread.start_new_thread( sendChat, (s, "sendChat" ) )
NameError: name 'thread' is not defined

Obvious, yes? You didn't import the thread module, so of course calling thread.start_new_thread() can't possibly work (you imported threading instead - which you should be using instead of the low-level thread module).