Redirect the standard error output to /dev/null in

2019-09-02 13:29发布

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'

标签: python linux
2条回答
Evening l夕情丶
2楼-- · 2019-09-02 14:22

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:
        if not 0 <= int(item) <= 255:
             return False
    except ValueError:
        return False # 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
查看更多
Bombasti
3楼-- · 2019-09-02 14:30

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:
   if not 0 <= int(item) <= 255:
       return False
except ValueError as e:
   return False
查看更多
登录 后发表回答