Python: Suppressing errors from going to commandline?

前端 未结 4 1076
粉色の甜心
粉色の甜心 2021-01-05 16:17

When I try to execute a python program from command line, it gives the following error. These errors do not cause any problem to my ouput. I dont want it to be displayed in

相关标签:
4条回答
  • 2021-01-05 16:53

    Redirect stderr to /dev/null.

    python somescript.py 2> /dev/null
    
    0 讨论(0)
  • 2021-01-05 16:54

    Here is a more readable, succinct solution for handling errors that are safe to ignore, without having to resort to the typical try/except/pass code block.

    from contextlib import suppress
    
    with suppress(IgnorableErrorA, IgnorableErrorB):
        do_something()
    
    0 讨论(0)
  • 2021-01-05 16:59

    Doesn't catching HTMLParseError work for you? If test.py is the name of your python file, it's propagated up to there, so it should.

    Here's an example how to suppress such an error. You might want to tweak it a bit to match your code.

    try:
        # Put parsing code here
    except HTMLParseError:
        pass
    

    You can also just suppress the error message by redirecting stderr to null, like Ignacio suggested. To do it in code, you can just write the following:

    import sys
    
    class DevNull:
        def write(self, msg):
            pass
    
    sys.stderr = DevNull()
    

    However, this is probably not be what you want, because from your error it looks like the script execution is stopped, and you probably want it to be continued.

    0 讨论(0)
  • 2021-01-05 17:15

    In python 3, @Boaz Yaniv's answer can be simplified as

    sys.stderr = object
    

    since every class in python3 is inherited from Object, so technically this would work, at least I've tried it by myself in python 3.6.5 environment.

    0 讨论(0)
提交回复
热议问题