Hello all,
I imagine that there are quite a few (old) sysadmins, developers and
Pythonistas lurking on this list who are also interested in this
question. I'm one of them, I suppose, and I couldn't help but want
to add a point or two.
Rich--I think you have gotten quite a bit of help so far in this
question (which you brought up a few weeks ago).
I will observe that you are encountering many of the problems
inherent in working with and relying on networked services.
Sometimes those ervices aren't available, sometimes the code on the
other side is broken, sometimes the code on your side is broken. I
learned an amusingly relevant expression from a very experienced
developer. 'My code inhabits a hostile universe.'
So, here are some tips that come to my mind as I read this thread.
* if you are writing a file where it is important that the file
is either written completely or not present, consider using
filesystem atomicity to guarantee that the data in the file are
good; here is an example:
set -e # -- exit whole script if any command fails
DATAFILE=my-critical-info
URL=http://some.flaky.org/information
curl --silent --fail --output "${DATAFILE}.tmp" -- "${URL}" \
&& mv -v "${DATAFILE}.tmp" "${DATAFILE}"
# -- if we made it here, $DATAFILE fetched $URL and wrote completely
if you don't understand what filesystem atomicity is and/or what
it affords you, it is worth it
* if you are reading a file that you know should have contents
check it for non-zero size before reading; depends on how
paranoid you are
* and, I'll pick on Dwight's solution (thank you for sharing your
example, Dwight)--there can be many sorts of strings which
contain four dots, so why not by a bit more assiduous and make
Python do the work for you; let's assume that your data are
normally valid IPs, then use the old easier to ask for
forgiveness approach
Instead of:
if len(result.split('.')) == 4:
Perhaps something like this (which assumes False, and/or
raises an error if something other than socket.error occurs):
import socket
def validate_ip(ipstr):
ipstr = ipstr.strip()
try:
packed = socket.inet_pton(socket.AF_INET,ipstr) # -- network
order
if ipstr == socket.inet_ntop(socket.AF_INET,packed): # -- back to
str
return True
except socket.error:
return False
return False
For those from the old school, you'll note that I used inet_pton()
and inet_ntop() instead of the rather venerable inet_aton() and
inet_ntoa(). Why, you might ask? Well, according to the ancient
rules of socket programming, the following is true (and ghastly, to
my mind):
>>> socket.inet_ntoa(socket.inet_aton('010.010.010.010'))
'8.8.8.8'
Octal? No thanks. I'll specify the address family, thank you very
much.
-Martin
--
Martin A. Brown
http://linux-ip.net/
_______________________________________________
PLUG mailing list
[email protected]
http://lists.pdxlinux.org/mailman/listinfo/plug