如何抑制一系列情节的输出
How to suppress output of a series of plots
我试图在下面的代码中抑制 output/plots 运行(因为我计划稍后调整绘图),但无论我尝试了什么,似乎都没有用.
我已经根据参考文章尝试了以下所有方法(我的代码乱七八糟,需要清理),但似乎没有任何效果。
- 添加分号
- 及格;声明
- 调整笔记本的环境条件
- 使用子流程函数和修改后的抑制函数
相关SO:
- Remove output of all subprocesses in Python without access to code
- Silence the stdout of a function in Python without trashing sys.stdout and restoring each function call
- Python: Suppress library output not using stdout
- IPython, semicolon to suppress output does not work
- https://github.com/ipython/ipython/issues/10794
dictionary_of_figures = OrderedDict()
dictionary_of_images = OrderedDict()
from contextlib import contextmanager
import sys, os
import subprocess
import inspect
import contextlib
import io
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import matplotlib.ticker as ticker
from collections import OrderedDict
def draw_year_close_plot(df, group_by_column_name, year):
reduced_range = df.loc[(df['Year'] == year)]
year_string = str(year)
# 0 - Setup
matplotlib.rc_file_defaults();
ax1 = sns.set_style("darkgrid"); #"style must be one of white, dark, whitegrid, darkgrid, ticks"
fig, ax1 = plt.subplots(figsize=(5,2));
# 1 - Create Closing Plot
lineplot = sns.lineplot(data = reduced_range['Close'], sort = False, ax=ax1);
pass;
ax1.xaxis.set_major_formatter(ticker.EngFormatter())
lineplot.set_title(company_name + str(" (")+ stock_ticker + str(") - ") + 'Historical Close & Volume - ' + year_string, fontdict= { 'fontsize': 8, 'fontweight':'bold'})
# 2 - Create Secondary Plot - Volume
ax2 = ax1.twinx();
ax2.grid(False);
sns.lineplot(data = reduced_range['Volume'], sort = False, ax=ax2, alpha=0.15);
pass;
return fig
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "last_expr"
#@contextmanager
#def suppress_stdout():
# with open(os.devnull, "w") as devnull:
# old_stdout = sys.stdout
# sys.stdout = devnull
# try:
# yield
# finally:
# sys.stdout = old_stdout
#@contextlib.contextmanager
#def nostdout():
# save_stdout = sys.stdout
# sys.stdout = io.BytesIO()
# yield
# sys.stdout = save_stdout
with contextlib.redirect_stdout(io.StringIO()):
for year in range(min_year,min_year+5):
dictionary_of_figures[year] = draw_year_close_plot(daily_df,'Year', year);
dictionary_of_images[year] = fig2img(dictionary_of_figures[year]);
有什么想法吗?
您似乎要求在 Jupyter 环境中抑制绘图。 %matplotlib inline
导致绘图在输出上呈现。如果你删除那条线,你将不会得到渲染的图,你将取回图对象(我在你的代码上测试过)。
一旦 Jupyter 中的内核拥有 运行,您就无法注释掉 %matplotlib inline
- 它会在内核中持续存在。您需要将其注释掉并重新启动内核,此时我想您会看到您想要的行为。
修改完绘图后,您可以重新打开 %matplotlib inline
并渲染更新后的绘图。
如果您需要打开和关闭 %matplotlib inline
,您需要对您的 Jupyter 环境有所了解。请参阅 this answer
更新:
我试了几个案例。如果将 %matplotlib
显式设置为 inline
以外的选项,效果会更好。这是用于说明的最少代码。我保留了所有与图形相关的代码,并在您的问题未提供值的地方编造数据,并打印 fig
的类型(这是您的 return 值)。我还明确设置了 %matplotlib notebook
。请注意,您应该 运行 %matplotlib --list
以确保这是您的选择之一。
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.ticker as ticker
df = pd.DataFrame({'Close': [1,2,3], 'Volume': [4,5,6]})
%matplotlib notebook
# matplotlib.rc_file_defaults() # We don't have your defaults file
ax1 = sns.set_style("darkgrid"); #"style must be one of white, dark, whitegrid, darkgrid, ticks"
fig, ax1 = plt.subplots(figsize=(5,2))
lineplot = sns.lineplot(data=df['Close'], sort = False, ax=ax1)
ax1.xaxis.set_major_formatter(ticker.EngFormatter())
lineplot.set_title("This is the Title")
ax2 = ax1.twinx()
ax2.grid(False)
sns.lineplot(data=df['Volume'], sort = False, ax=ax2, alpha=0.15)
print(type(fig))
我试图在下面的代码中抑制 output/plots 运行(因为我计划稍后调整绘图),但无论我尝试了什么,似乎都没有用.
我已经根据参考文章尝试了以下所有方法(我的代码乱七八糟,需要清理),但似乎没有任何效果。
- 添加分号
- 及格;声明
- 调整笔记本的环境条件
- 使用子流程函数和修改后的抑制函数
相关SO:
- Remove output of all subprocesses in Python without access to code
- Silence the stdout of a function in Python without trashing sys.stdout and restoring each function call
- Python: Suppress library output not using stdout
- IPython, semicolon to suppress output does not work
- https://github.com/ipython/ipython/issues/10794
dictionary_of_figures = OrderedDict()
dictionary_of_images = OrderedDict()
from contextlib import contextmanager
import sys, os
import subprocess
import inspect
import contextlib
import io
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import matplotlib.ticker as ticker
from collections import OrderedDict
def draw_year_close_plot(df, group_by_column_name, year):
reduced_range = df.loc[(df['Year'] == year)]
year_string = str(year)
# 0 - Setup
matplotlib.rc_file_defaults();
ax1 = sns.set_style("darkgrid"); #"style must be one of white, dark, whitegrid, darkgrid, ticks"
fig, ax1 = plt.subplots(figsize=(5,2));
# 1 - Create Closing Plot
lineplot = sns.lineplot(data = reduced_range['Close'], sort = False, ax=ax1);
pass;
ax1.xaxis.set_major_formatter(ticker.EngFormatter())
lineplot.set_title(company_name + str(" (")+ stock_ticker + str(") - ") + 'Historical Close & Volume - ' + year_string, fontdict= { 'fontsize': 8, 'fontweight':'bold'})
# 2 - Create Secondary Plot - Volume
ax2 = ax1.twinx();
ax2.grid(False);
sns.lineplot(data = reduced_range['Volume'], sort = False, ax=ax2, alpha=0.15);
pass;
return fig
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "last_expr"
#@contextmanager
#def suppress_stdout():
# with open(os.devnull, "w") as devnull:
# old_stdout = sys.stdout
# sys.stdout = devnull
# try:
# yield
# finally:
# sys.stdout = old_stdout
#@contextlib.contextmanager
#def nostdout():
# save_stdout = sys.stdout
# sys.stdout = io.BytesIO()
# yield
# sys.stdout = save_stdout
with contextlib.redirect_stdout(io.StringIO()):
for year in range(min_year,min_year+5):
dictionary_of_figures[year] = draw_year_close_plot(daily_df,'Year', year);
dictionary_of_images[year] = fig2img(dictionary_of_figures[year]);
有什么想法吗?
您似乎要求在 Jupyter 环境中抑制绘图。 %matplotlib inline
导致绘图在输出上呈现。如果你删除那条线,你将不会得到渲染的图,你将取回图对象(我在你的代码上测试过)。
一旦 Jupyter 中的内核拥有 运行,您就无法注释掉 %matplotlib inline
- 它会在内核中持续存在。您需要将其注释掉并重新启动内核,此时我想您会看到您想要的行为。
修改完绘图后,您可以重新打开 %matplotlib inline
并渲染更新后的绘图。
如果您需要打开和关闭 %matplotlib inline
,您需要对您的 Jupyter 环境有所了解。请参阅 this answer
更新:
我试了几个案例。如果将 %matplotlib
显式设置为 inline
以外的选项,效果会更好。这是用于说明的最少代码。我保留了所有与图形相关的代码,并在您的问题未提供值的地方编造数据,并打印 fig
的类型(这是您的 return 值)。我还明确设置了 %matplotlib notebook
。请注意,您应该 运行 %matplotlib --list
以确保这是您的选择之一。
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.ticker as ticker
df = pd.DataFrame({'Close': [1,2,3], 'Volume': [4,5,6]})
%matplotlib notebook
# matplotlib.rc_file_defaults() # We don't have your defaults file
ax1 = sns.set_style("darkgrid"); #"style must be one of white, dark, whitegrid, darkgrid, ticks"
fig, ax1 = plt.subplots(figsize=(5,2))
lineplot = sns.lineplot(data=df['Close'], sort = False, ax=ax1)
ax1.xaxis.set_major_formatter(ticker.EngFormatter())
lineplot.set_title("This is the Title")
ax2 = ax1.twinx()
ax2.grid(False)
sns.lineplot(data=df['Volume'], sort = False, ax=ax2, alpha=0.15)
print(type(fig))