运行bokeh serve my_python_script.py时,如何让print输出显示在终端?
print() Output in Bokeh Server Terminal Hey there! I’ve run into this exact issue with Bokeh Server before—super frustrating when your print statements vanish into thin air. Let’s break down why this happens and how to get your messages showing up in the terminal again.
Why print() Doesn’t Show Up
By default, Bokeh Server redirects standard output (stdout) to its internal logging system. That means your regular print() calls aren’t sent directly to the terminal you launched the server from—they’re routed through Bokeh’s logger instead, which might not display them depending on the default log level.
Solutions to Try
1. Configure Bokeh Logging in Your Script
Add this code at the very top of your my_python_script.py to force Bokeh to log your print messages to the terminal:
import logging from bokeh.util.logconfig import basicConfig # Set logging level to INFO and format messages to show just your text basicConfig(level=logging.INFO, format="%(message)s")
This tells Bokeh to capture stdout (including print() output) and log it at the INFO level, which will display in your terminal as long as the server’s log settings allow it.
2. Use Bokeh’s Logging Directly (Recommended)
Instead of relying on print(), use Bokeh’s built-in logging system for more control. This is the "proper" way to handle messages in Bokeh Server apps:
import logging logger = logging.getLogger(__name__) # Replace print() with these calls logger.info("Your debug or status message here") logger.warning("This is a warning that will stand out in the terminal") logger.error("Critical error—needs immediate attention")
You can adjust the log level (DEBUG, INFO, WARNING, ERROR) to control what shows up, which is way more flexible than plain print().
3. Adjust the Bokeh Server Launch Command
If you don’t want to modify your script, add the --log-level=info flag when starting the server. This ensures the server displays INFO-level logs (which includes your redirected print() output):
bokeh serve my_python_script.py --log-level=info
If your messages are still missing, try setting the log level to debug—it will show even more detailed output, including lower-priority messages.
4. For Callback Functions
If your print() calls are inside Bokeh callback functions (like button clicks or slider updates), all the above methods still work! The stdout from callbacks is also routed through Bokeh’s logging system, so configuring the log level or using the logger will make those messages visible too.
内容的提问来源于stack exchange,提问作者Javier Guzmán

