'How to suppress automatically generated output from a Python code?
I want to suppress auto generated output from this line of code:
cp = client.fetch_market_depth(a)["Data"][0]['LastTradedPrice']
Here client.fetch_market_depth() is part of coding API developed by 5paisa.
It's using log_response to output debug messages.
It outputs "current time | Success"
After googling and using code from this link of Stack Overflow, I am using following code. Still it is unable to suppress the output. What option I have now? I use Python 3.
After I receive the suggestion in comment, I edited the code and redirected output from stderr too. Still it's printing same output.
class HiddenPrints:
def __enter__(self):
self._original_stdout = sys.stdout
self._original_stderr = sys.stderr
sys.stdout = open(os.devnull, 'w')
sys.stderr = open(os.devnull, "w")
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout = self._original_stdout
sys.stderr = self._original_stderr
SC1 = 20374
a=[{"Exchange":"N","ExchangeType":"C","ScripCode":SC1},]
with HiddenPrints():
cp = client.fetch_market_depth(a)["Data"][0]['LastTradedPrice']
Solution 1:[1]
Looks like that the problem is that the py5paisa's logging module gets the reference to the real sys.stdout before HiddenPrints replaces it.
You need to disable the logger by importing it and calling logger.disable(""). And after exiting the context, enable it with logger.enable("").
If you also want to ignore any exceptions, you need to return True on exit.
class HiddenPrints:
def __enter__(self):
self._original_stdout = sys.stdout
self._original_stderr = sys.stderr
sys.stdout = open(os.devnull, 'w')
sys.stderr = open(os.devnull, "w")
from loguru import logger
logger.disable("") #disable the logger
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout = self._original_stdout
sys.stderr = self._original_stderr
from loguru import logger
logger.enable("") #enable the logger
return True #optionally also ignore exceptions
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
