I am trying to call a function inside another class function in Python. However, I am getting the error that global name is not defined. I don't know what to do as I can't figure out what's the issue.
The error is:
NameError: global name 'sendCmdWaitForRaffleResponse' is not defined
Here is the code I have written:
Class T:
def connect(self,ipAddr,portNum):
try:
print "Check1"
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ipAddr,portNum))
s.settimeout(1000*30)
response=s.recv(8192)
print response
cmd="some command"
s.send(cmd)
print 'check'
response=s.recv(1024)
print response
#time.sleep(5)
except Exception as e:
print e
def Send(self,command):
result ="ok"
try:
print "start"
if command.startswith("#"):
#print result
return result
elif not command:
return result
print 'yes'
result=sendCmdWaitResponse(command)
except Exception as e:
print (e)
return result
def sendCmdWaitResponse(self,cmd):
print "Running"
s.send(cmd)
while true:
response=s.recv(1024)
response=+ '\n'
print response
print "Leaving"
return sb.getvalue()
if __name__ == "__main__":
test=T()
a='some command'
test.Connect(ipaddr,port)
test.Send(a)
You need self.
result=self.sendCmdWaitResponse(command)
Change
result=sendCmdWaitResponse(command)
to
result=self.sendCmdWaitResponse(command)
Your code seems to have many typo: This is the fix I have done. I don't know what is your expected output. Please add the valid code:
import socket
class T():
def __init__(self, ipAddr, portNum):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self,ipAddr,portNum):
try:
print "Check1"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ipAddr,portNum))
s.settimeout(1000*30)
response=s.recv(8192)
print response
cmd="some command"
s.send(cmd)
print 'check'
response=s.recv(1024)
print response
#time.sleep(5)
except Exception as e:
print e
def Send(self, command):
result ="ok"
try:
print "start"
if command.startswith("#"):
#print result
return result
elif not command:
return result
print 'yes'
result= self.sendCmdWaitResponse(command)
except Exception as e:
print (e)
return result
def sendCmdWaitResponse(self,cmd):
print "Running"
self.s.send(cmd)
while True:
response= self.s.recv(1024)
response=+ '\n'
print response
print "Leaving"
return sb.getvalue()
if __name__ == "__main__":
a='some command'
ipAddr = ""
port = 1000
test = T(ipAddr, port)
test.connect(ipAddr,port)
test.Send(a)
Related
I'm having trouble with this error:
Exception in thread StompReceiverThread-1 (most likely raised during
interpreter shutdown):
That is no traceback at all.. just that.
Usualy everything works fine but rarely it happens and then the action does not conclude.
Any tips?
My code:
class Listener(stomp.ConnectionListener):
def __init__(self, conn, request):
self.conn = conn
self.request = request
def on_error(self, headers, message):
global WAITING_RESPONSE
print('received an error: ' + message)
WAITING_RESPONSE = False
def on_message(self, headers, message):
global WAITING_RESPONSE
try:
msg = json.loads(message)
if str(msg.get('transaction_id','')) == str(CURRENT_ID):
printDebugLine('Queue response:'+str(message))
manageQueueResponse(message,self.request)
WAITING_RESPONSE = False
self.conn.ack(headers['message-id'], '11')
except stomp.exception.ConnectFailedException:
print('Stomp error on message')
sys.exit(3)
except Exception as e:
print('ERROR: %s' % str(e))
sys.exit(3)
class Queue(object):
def __init__(self):
self.host = xx
self.port = xx
self.login = xx
self.passwd = xx
self.request = {}
self.start()
def start(self):
try:
self.conn = stomp.Connection(host_and_ports=[(self.host, self.port)])
self.conn.start()
self.conn.connect(self.login, self.passwd, wait=True)
self.conn.set_listener('xx', Listener(self.conn, self.request))
self.conn.subscribe(destination='xx', id='xx', ack='xx')
except stomp.exception.ConnectFailedException:
print('ERROR: unable to connect')
sys.exit(3)
except Exception as e:
print('ERROR: %s' % str(e))
sys.exit(3)
def send(self, data):
global CURRENT_ID
while WAITING_RESPONSE:
time.time(0.1)
try:
CURRENT_ID = str(uuid.uuid4())
data.update({'transaction_id': CURRENT_ID})
b = json.dumps(data)
self.request.update(data)
printDebugLine('Queue request:'+str(data))
self.conn.send(body=b, destination='xx')
timeout(data,self.request,29)
except stomp.exception.ConnectFailedException:
print('ERROR: unable to connect')
except Exception as e:
print('ERROR: %s' % str(e))
It looks like your main program is exiting, the interpreter is cleaning up things, but the stomp receiver thread was not shutdown first. The receiver thread goes to do something but basic modules are no longer available, so it gives an exception message, but cannot print a Traceback because that fuctionality is no longer available due to the program exiting.
Look at why the main program would be exiting.
I implemented a simple network 'game' in Python - server draws a random number, and then the client tries to guess it. My application works great, when the client guesses the number, it disconnects from server (it is handled on client's side).
However, after the proper guess, the number is still the same. I would like to modify the application, such that when the client guesses the number, the server should then rand a new number, so other clients should guess the new one. How can I do this?
Some template, just to draw an attention to the problem:
#!/usr/bin/env python
from random import randint
import socket, select
from time import gmtime, strftime
import threading
import sys
class Handler(threading.Thread):
def __init__(self, connection, randomnumber):
threading.Thread.__init__(self)
self.connection = connection
self.randomnumber = randomnumber
def run(self):
while True:
try:
data = self.connection.recv(1024)
if data:
print data
try:
num = int(data)
if Server.guess(num) :
msg = "You won! This is the right number!"
self.connection.send(msg)
break
else :
msg = "Try again!"
self.connection.send(msg)
except ValueError, e:
msg = "%s" % e
self.connection.send(msg)
else:
msg = "error"
self.connection.send(msg)
except socket.error:
self.connection.close()
break
self.connection.close()
class Server:
def __init__(self, ip, port):
self.ip = ip
self.port = port
self.address = (self.ip, self.port)
self.server_socket = None
self.randnum = randint(1, 100)
#classmethod
def guess(cls, no):
if cls.randnum == no:
cls.randnum = randint(1, 1000)
result = True
else:
result = False
return reslut
def run(self):
try:
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.bind((self.ip, self.port))
self.server_socket.listen(10)
print 'Num is %s' % self.randnum
while True:
connection, (ip, port) = self.server_socket.accept()
c = Handler(connection, self.randnum)
c.start()
except socket.error, e:
if self.server_socket:
self.server_socket.close()
sys.exit(1)
if __name__ == '__main__':
s = Server('127.0.0.1', 1234)
s.run()
Generate the random number that is shared between both server and all the client, there should be only instance of this, hence this should be class attribute.
Add a class function guess which return False upon incorrect guess and upon correct guess changes the randnum and returns True
class Server:
randnum = randint(1, 1000) # class attribute created
#classmethod
def guess(cls, no): # To be used "guess" if `no` attribute if the same as `cls.randnum`
if cls.randnum == no:
cls.randnum = randint(1, 1000)
result = True
else:
result = False
return result
def __init__(self, ip, port):
# ...
The client should call this Server.guess function each time.
Actually your issue comes from the fact that you create randnum as an instance method (see your self.randnum) as #shanmuga explained, if you simply declare it as being a class attribute, and remove the instance method it solves your issue (i.e. declaring it in the class directly).
As a side issue (not being an expert on socket), when you send message to the client, you might want to encode them as a byte object (in the run method of Handler, I changed self.connection.send(msg) to self.connection.send(msg.encode())). Also note that I used Python 3.6 (which mainly change the style of print statements)
See the code below:
#!/usr/bin/env python
from random import randint
import socket, select
from time import gmtime, strftime
import threading
import sys
class Handler(threading.Thread):
def __init__(self, connection, randomnumber):
threading.Thread.__init__(self)
self.connection = connection
self.randomnumber = randomnumber
def run(self):
while True:
try:
data = self.connection.recv(1024)
if data:
print(data)
try:
num = int(data)
if Server.guess(num) :
msg = "You won! This is the right number!"
self.connection.send(msg.encode())
break
else :
msg = "Try again!"
self.connection.send(msg.encode())
except ValueError as e:
msg = "%s" % e
self.connection.send(msg.encode())
else:
msg = "error"
self.connection.send(msg.encode())
except socket.error:
self.connection.close()
break
self.connection.close()
class Server:
randnum = randint(1,100)
def __init__(self, ip, port):
self.ip = ip
self.port = port
self.address = (self.ip, self.port)
self.server_socket = None
#classmethod
def guess(cls, no):
if cls.randnum == no:
cls.randnum = randint(1, 1000)
print("New number is ", cls.randnum )
result = True
else:
result = False
return result
def run(self):
try:
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.bind((self.ip, self.port))
self.server_socket.listen(10)
print('Num is %s' % self.randnum)
while True:
connection, (ip, port) = self.server_socket.accept()
c = Handler(connection, self.randnum)
c.start()
except socket.error as e:
if self.server_socket:
self.server_socket.close()
sys.exit(1)
if __name__ == '__main__':
s = Server('127.0.0.1', 1234)
s.run()
self.handlers.append(ConnHandler(sock, self.handlers))I'm new to python and I tried to write a simple socket server to test stuff out and get to know the language better.
import asyncore
import socket
import json
class ConnHandler(asyncore.dispatcher_with_send):
def __init__(self, conn, handlerlist):
asyncore.dispatcher_with_send.__init__(self, conn)
self.handlers = handlerlist
def handle_close(self):
self.close()
print 'Socket closed'
if(self.handlers.count(self) > 0):
self.handlers.remove(self);
def handle_read(self):
data = ''
more = True
while more:
try:
data += self.recv(1024)
except socket.error, e:
more = False
if data == '':
return
try:
message = json.loads(data)
except ValueError:
self.send('Invalid JSON\n')
return
print message
class TestServer(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((host, port))
self.listen(5)
self.handlers = []
def handle_accept(self):
pair = self.accept()
if pair is not None:
sock, addr = pair
print 'Incoming connection from %s' % repr(addr)
self.handlers.append(ConnHandler(sock, self.handlers))
def sendToAll(self, string):
for h in self.handlers:
h.send(string + '\n')
server = TestServer('localhost', 55555)
asyncore.loop()
My problem is the following.
If I connect to the server with telnet and then quit telnet to close the connection, python just spams 'Socket closed' in the terminal. How can I fix this? Are there obvious beginner mistakes in the above code?
handle_close is not meant to detect if peer is disconnected, you get this information in handle_read if .recv call returns an empty string. Then you can close the socket, and then handle_close is called.
Here is a modified version of your code:
def handle_close(self):
print 'Socket closed'
if(self.handlers.count(self) > 0):
self.handlers.remove(self);
def handle_read(self):
data = ''
more = True
while more:
try:
new_data = self.recv(1024)
if not new_data:
self.close()
return
else:
data += new_data
except socket.error, e:
more = False
if data == '':
return
try:
message = json.loads(data)
except ValueError:
self.send('Invalid JSON\n')
return
print message
to demonstrate problem I've prepared simple code:
from multiprocessing import Pool
class MyError(Exception):
def __str__(self):
return repr("Error msg: " + self.args[0])
def pool_function(msg):
print msg
raise MyError(msg)
return 0
def some_function():
my_pool = Pool(2)
msg = ['first', 'second']
my_pool.map(pool_function, msg)
if __name__ == '__main__':
try:
some_function()
except MyError, msg:
print msg
In this particular example as output I get:
first
second
'Error msg: first'
but I need rather:
first
second
'Error msg: first'
'Error msg: second'
Problem is that on the level of the main function I try to get access to all error messages which are unique, rather than handling it on level of pool_function but I get only first error msg. Unfortunately the real code with which I work is much more complex so is rather hard to do something with the structure of this code which is demonstrated in example. I need some clean and straight forward solution to get all error messages and process it on the level of main function.
Thanks in advice for any solutions.
You have to put try~ except in your pool_function not __main__. If no, __main__ will stop after the first except raised and left no chance for the second one to run. This is following what you are trying:
def pool_function(msg):
print msg
try:
raise MyError(msg)
except:
return MyError(msg)
def some_function():
my_pool = Pool(2)
msg = ['first', 'second']
return my_pool.map(pool_function, msg)
if __name__ == '__main__':
try:
msg= some_function()
except MyError, msg:
print msg
It works, but seem not a good way, so:
def pool_function(msg):
print msg
try:
# do something
raise MyError(msg)
except:
return 0,MyError(msg)
else:
return 1,# some result
def some_function():
my_pool = Pool(2)
msg = ['first', 'second']
return return my_pool.map(pool_function, msg)
if __name__ == '__main__':
msg = some_function()
for result in msg:
if result[0]:
# do something when it run successfully
elif not result[0]:
print result[1]
# do something when it got errors
I created the following class that I want to have a socket member within it and then want to use member functions to connect, close, send, and receive.
class Connection:
Kon = ""
SSLx = ""
def Close(self):
try:
self.Kon.close()
return True
except:
return False
def Send(self,Message):
try:
self.Kon.write(Message)
return True
except Exception,e:
print e
return False
def Recieve(self):
try:
Response = self.Kon.recv(10240)
return Response
except:
return False
#Conenct Function Makes a SSL connection with the node
def Connect(self,Link):
self.SSLx = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Ip = Link[0].replace("'",'')
print Ip
Port = int(Link[1])
try:
self.SSLx.connect((Ip,Port))
return True
except Exception,e:
print "Connection Attempt Failed"
self.Kon = socket.ssl(SSLx)
return False
I ran the .Connect function successfully, but after that when I try the Send function it says 'str' object does not have a write member.
Any ideas on how to get this done?
There seems to have been a small error from a debugging process I did, I had shifted one of the lines that initialized the Kon variable few lines below. The following is the corrected class.
class Connection:
Kon = ""
SSLx = ""
def Close(self):
try:
self.Kon.close()
return True
except:
return False
def Send(self,Message):
try:
self.Kon.write(Message)
return True
except Exception,e:
return False
def Recieve(self):
try:
Response = self.Kon.read(10240)
return Response
except Exception,e:
print e
return False
#Conenct Function Makes a SSL connection with the node
def Connect(self,Link):
self.SSLx = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Ip = Link[0].replace("'",'')
print Ip
Port = int(Link[1])
try:
self.SSLx.connect((Ip,Port))
self.Kon = socket.ssl(self.SSLx)
return True
except Exception,e:
print e
print "Connection Attempt Failed"
return False