I'm trying to catch an error in memcached when this one is down with python:
import memcache
import socket
mc = memcache.Client(['127.0.0.1:11211'], debug=1)
try:
print mc.get('gfdsgf')
except socket.error:
print 'error'
But I still have this error in my console:
MemCached: MemCache: inet:127.0.0.1:11211: connect: Connection refused. Marking dead.
None
this is not really an error that you can catch this is just a log, and it's displayed because you have the debug parameter to 1, so turn off the debug parameter. And as you can see you still get None from your print that mean your key doesn't exist
Try something like that:
import memcache
mc = memcache.Client(['127.0.0.1:11211'], debug=0)
try:
print mc.get('gfdsgf')
except (mc.MemcachedKeyTypeError, mc.MemcachedKeyNoneError,
TypeError, mc.MemcachedKeyCharacterError,
mc.MemcachedKeyError, mc.MemcachedKeyLengthError,
mc.MemcachedStringEncodingError):
print 'error'
Related
I'm writing test script for a TCP Server in Python 3.8.
The script worka well, but now I'm tring to implemente a more efficient error catching in order to identify timeout error.
To do that I started to catch the errors and the timeout error for the socket connect.
This is my SocketConnect function:
def SocketConnect( host, port ):
global socketHandle
opResult = errorMessagesToCodes['No Error']
# Set Socket Timeout
socketHandle.settimeout(1)
logging.debug("Connect")
try:
socketHandle.connect((host, port))
except socketHandle.error as e:
opResult = errorMessagesToCodes['Socket Error']
logging.error("!!! Socket Connect FAILED: %s" % e)
return opResult
The socket handler is valid and, in order to test the timeout, I disable the server.
After one second after the connect the code goes to the except but I get this error:
socket.connect((host, port))
socket.timeout: timed out
During handling of the above exception, another exception occurred:
except socket.error as e:
AttributeError: 'socket' object has no attribute 'error'
Is there something missing?
Because I don't understand why socket object ha no attribute error. I think this is a standard error for socket interface.
Thanks in advance for the help.
UPDATE:
I tried to do a basic test (starting from a blank project): only a socket create and a socket connect (with a server not in listening mode) to simulate a timeout.
This is the code:
import socket
import logging
try:
socketHandle = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socketHandle.error as e:
logging.error("Socket Create FAILED: %s" % e)
socketHandle.settimeout(1)
try:
socketHandle.connect(('localhost', 2000))
except socketHandle.error as e:
logging.error("!!! Socket Connect FAILED: %s" % e)
The connect goes into timeout but I still get the error:
except socketHandle.error as e:
AttributeError: 'socket' object has no attribute 'error'
I really don't know what is happening.
UPDATE 2:
I made some other tests, and if I use the try-catch inside the connect function I get the error but if I use the try catch in the main a did not get any error.
Best regards,
Federico
The error is due to you redefining the module name socket; which is what contains socket.error. You are trying to access module level constants (in this case error from the socket module), from a socket object. You could also tighten the error handling to only catch a timeout. This may be needed anyhow, as it appears socket.error does not cover socket.timeout. Changing your socket name should solve the issue:
def SocketConnect(socx, host, port ):
opResult = errorMessagesToCodes['No Error']
# Set Socket Timeout
socx.settimeout(1)
logging.debug("Connect")
try:
socx.connect((host, port))
except socket.timeout as e:
opResult = errorMessagesToCodes['Socket Error']
logging.error("!!! Socket Connect FAILED: %s" % e)
return opResult
I was wondering if there is an easy way of knowing whether a connection to an FTP server is still active using ftplib.
So if you have an active connection like this:
import ftplib
ftp = ftplib.FTP("ftp.myserver.com", "admin", "pass123")
is there something like the following pseudo code that can be queried to check if the connection is still active?
if ftp.is_connected() == True:
print "Connection still active"
else:
print "Disconnected"
You could try retrieving something from the server, and catching any exceptions and returning whether or not it's connected based on that.
For example:
def is_connected(ftp_conn):
try:
ftp_conn.retrlines('LIST')
except (socket.timeout, OSError):
return False
return True
This simple example will print the 'LIST' results to stdout, you can change that by putting your own callback into the retrlines method
(Make sure you set a timeout in the initial FTP object construction, as the default is for it to be None.)
ftp = ftplib.FTP("ftp.gnu.org", timeout=5, user='anonymous', passwd='')
I have a function that returns the DB connection handler from MongoDB. I have various other functions that makes a call to the DB, I figure let's throw the connection handler into a function so I don't have to define it in every function.
Does this look right? I guess my question is, if it can't make a connection to the DB server, it will print both messages Could not connect to server and No hosts found How can I go about only printing "Could not connect to the server."
def mongodb_conn():
try:
conn = pymongo.MongoClient()
except pymongo.errors.ConnectionFailure, e:
print "Could not connect to server: %s" % e
return conn
def get_hosts()
try:
conn = mongodb_conn()
mongodb = conn.dbname.collection
b = []
hosts_obj = mongodb.find({'_id': 'PR'})
for x in hosts_obj:
print x
except:
print "No hosts found"
get_hosts()
Move your conn = mongodb_conn() call out of the try .. except handler, and test if None was returned:
def get_hosts()
conn = mongodb_conn()
if conn is None:
# no connection, exit early
return
try:
mongodb = conn.dbname.collection
b = []
hosts_obj = mongodb.find({'_id': 'PR'})
for x in hosts_obj:
print x
except:
print "No hosts found"
You should, at all cost, avoid using a blanket except however; you are catching everything now, including memory errors and keyboard interrupts, see Why is "except: pass" a bad programming practice?
Use specific exceptions only; you can use one except statement to catch multiple exception types:
except (AttributeError, pymongo.errors.OperationFailure):
or you can use multiple except statements handle different exceptions in different ways.
Limit the exception handler to just those parts of the code where the exception can be thrown. The for x in hosts_obj: loop for example is probably not going to throw an AttributeError exception, so it should probably not be part of the try block.
Note that you'll need to adjust your mongodb_conn() function to not try and use the conn local if it has never been set; you'll get an UnboundLocal error if you do:
def mongodb_conn():
try:
return pymongo.MongoClient()
except pymongo.errors.ConnectionFailure, e:
print "Could not connect to server: %s" % e
Now the function returns the connection if successful, None if the connection failed.
You can also check if the server is available
like this:
from pymongo.errors import ConnectionFailure
client = MongoClient()
try:
# The ismaster command is cheap and does not require auth.
client.admin.command('ismaster')
except ConnectionFailure:
print("Server not available")
I tried executing this code, but am getting an error message saying "Invalid syntax".
Please help me out, since am new to this.
#import socket module
from socket import *
connectonSocket.close()
except IOError:
connectionSocket.send('\nHTTP/1.1 404 Not Found\n\n')
#Close client socket
connectionSocket.close()
serverSocket.close()
Please see this informative TutorialsPoint page for a great explanation of try/except/else/finally Python code!
Your code should be:
#import socket module
from socket import *
try:
connectonSocket.open()
except IOError:
connectionSocket.send('\nHTTP/1.1 404 Not Found\n\n')
#Close client socket
finally:
connectionSocket.close()
serverSocket.close()
And if you are copying and pasting your code into cmd/terminal you cannot have blank lines (If you do you'll get an indentation error).
try/except/finally
TRY:
Means to 'try' to do something, ie. call a function, method, etc.
EXCEPT (you can have multiple excepts):
Means if your 'try' code did NOT work, do 'this' in response.
FINALLY:
Means do 'this' stuff whether or not you 'tried' and succeeded, or 'excepted'.
I am trying to have a client connect to my server, and have a stream of communication between them. The only reason the connection should break is due to network errors, or unless the client wants to stop talking.
The issue I am running into is keeping the handler in a tight loop, and parsing the JSON.
My server code is :
#!/usr/bin/env python
import SocketServer
import socket
import json
import time
class MyTCPServer(SocketServer.ThreadingTCPServer):
allow_reuse_address = True
class MyTCPServerHandler(SocketServer.BaseRequestHandler):
def handle(self):
while 1:
try:
networkData = (self.request.recv(1024).strip())
try:
jsonInputData = json.loads(networkData)
print jsonInputData
try:
if jsonInputData['type'] == 'SAY_HI':
print "HI"
except Exception, e:
print "no hi"
pass
try:
if jsonInputData['type'] == 'GO_AWAY':
print "Going away!"
except Exception, e:
print "no go away"
pass
except Exception, e:
pass
#time.sleep(0.001)
#print "JSON Error", e
except Exception, e:
#time.sleep(0.001)
pass
#print "No message", e
server = MyTCPServer(('192.168.1.115', 13373), MyTCPServerHandler)
server.serve_forever()
My client code is simple :
#!/usr/bin/env python
import socket
import json
import time
import sys
hostname = '192.168.1.103'
port = 13373
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((hostname,port))
except Exception, e:
print "Error, could not open socket: ", e
data = {'type':'SAY_HI'}
sock.send(json.dumps(data))
data = {'type':'SAY_BYE'}
sock.send(json.dumps(data))
Sometimes I'll see the messages being sent, "SAY_HI" and "SAY_BYE", but most of the times, no data is being displayed on the server side.
This question is really not clear, but calling self.request.recv(1024) is very likely not what you want to do. You're eliminating all of the nice application-level handling that TCP will happily do for you. If you change that to self.request.recv(8) or a similarly very small number (such that recv() returns whenever it receives data, and doesn't try to fill your buffer), you may get better results.
Ultimately this is super-simplistic change, even if it works, that will not work in a larger context. You will need to be handling exceptions from your json parser on the server side and waiting for more data until an entire well-formed message is received.
This is a hopelessly more complex subject than will be handled generally in any SO answer. If you're going to be doing any amount of raw sockets programming, you absolutely must own a copy of Unix Network Programming, Volume 1.