I have created the following script ( Python version 2.x ) in order to verify the IP address
in case the IP validation is passed the script will print OK
else the script will print Fail
the validation is very well ,
but what I don't want to print is the errors that comes from the exception ( see the Exe of the script ) ,
I just want to print OK or Fail , and redirect the standard error to null
please advice what need to update in my script to do that?
#!/usr/bin/python
import commands
import subprocess
import os
import re
import socket
def validIP(address):
parts = address.split(".")
if len(parts) != 4:
return False
for item in parts:
if not 0 <= int(item) <= 255:
return False
try:
socket.inet_aton(address)
return True
except socket.error:
return False
f = open('/dev/null', 'w')
sys.stdout = f
f.close()
address = raw_input("Please enter IP address : ")
res = validIP(address)
if res == True:
print"OK"
else:
print "Fail"
Exe the script: ( from Linux red-hat machine version 6 )
./Check_IP_Address.py
Please enter IP address : 192.9.200.WRONG
Traceback (most recent call last):
File "./Check_IP_Address.py", line 37, in <module>
res = validIP(address)
File "./Check_IP_Address.py", line 23, in validIP
if not 0 <= int(item) <= 255:
ValueError: invalid literal for int() with base 10: 'WRONG'
It looks like you don't know how to properly catch exceptions which makes me wonder if silencing stderr is within your range - you shouldn't just program by just copy-pasting examples, you should strive to understand the code you write. If you want to silence it by catching the exception you just catch it:
Note that you probably shouldn't silence errors without having a plan on how to proceed successfully in face of errors. From the zen of python:
The second is to mean that they are explicitely silence by actually handling the exception. If you can't handle the exception it is probably better to just drop out and get a traceback.
If you go for silencing
stderr
anyway (which you probably shouldn't, because that will silence errors that you don't handle which means you'll not know why your program all the suddenly just drops out if something goes wrong) you could replace by openingdev/null
anddup2
the file descriptor overSTDERR_FILENO
(ie2
). For exampleAccording to your statements, catching the ValueError exception would solve your problem. You shouldn't just leave the
Errors or Exceptions
alone. You should catch them directly.