Skip to content Skip to sidebar Skip to footer

Redirect The Standard Error Output To /dev/null In Python

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 prin

Solution 1:

According 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.

try:
   ifnot0 <= int(item) <= 255:
       returnFalseexcept ValueError as e:
   returnFalse

Solution 2:

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:

for items in parts:
    try:
        ifnot0 <= int(item) <= 255:
             returnFalseexcept ValueError:
        returnFalse# probably the correct thing to do if `item` is not convertible to int.

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:

  • Errors should never pass silently.
  • Unless explicitly silenced.

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 opening dev/null and dup2 the file descriptor over STDERR_FILENO (ie 2). For example

import os

f = open("/dev/null", "w")

os.dup2(f.fileno(), 2)

f.close()

f.fubar # this will fail and raise exception - which you shouldn't see

Post a Comment for "Redirect The Standard Error Output To /dev/null In Python"