Dro*_*ror 7 wolfram-mathematica messages
在我写的一个模块中,我有很多(用于开发和测试阶段)Print["Messages"].我有两个问题:
Pil*_*lsy 12
我喜欢始终保持带有前缀的全局变量$,以及没有前缀的函数,所以我写道:
debugPrint[args___] := $debugPrintFunction[args]
$debugPrintFunction = Print[##] &
Run Code Online (Sandbox Code Playgroud)
然后你可以debugPrint像你Print现在使用的那样使用.当您想要摆脱调试消息时,您只需取消设置变量:
$debugPrintFunction = .
Run Code Online (Sandbox Code Playgroud)
这样做有一些好处.一个是你可以用来Block在本地打开和关闭调试:
In[1]:= foo[x_] := (debugPrint[x]; x+1)
In[2]:= foo[3]
3
Out[2]= 4
In[3]:= Block[{$debugPrintFunction}, foo[3]
Out[3]= 4
Run Code Online (Sandbox Code Playgroud)
你甚至可以在本地$debugPrintFunction做一些其他的事情,比如拿起的Sow值Reap,或者在其他地方引导调试信息,比如
strm = OpenWrite["your/log/path/here", InputForm];
Block[{$debugPrintFunction = Write[strm, ##]},
foo[3]];
Close[strm];
Run Code Online (Sandbox Code Playgroud)
明智地使用,提供的动态范围Block允许以相对安全和受控的方式使用全局变量.
我的旧代码使用像Pillsy描述的方法.
最近我使用的头部通常没有任何规则,例如:
...
debugPrint[expr]
...
Run Code Online (Sandbox Code Playgroud)
然后有第二个功能:
Attributes[PrintDebug]={HoldAll}
PrintDebug[expr_] := Block[{debugPrint = Print}, expr]
Run Code Online (Sandbox Code Playgroud)
然后当我想看到调试输出时,我可以在输入周围包装PrintDebug:
PrintDebug[MyFunction[1,2,3]]
Run Code Online (Sandbox Code Playgroud)
或者,更常见的是
MyFunction[1,2,3] // PrintDebug
Run Code Online (Sandbox Code Playgroud)
因为我发现后缀形式更容易添加/删除,更好地将焦点放在主函数上.
我通常会在我的函数中安装一个详细的选项,如果需要调试,可以打开/关闭它.请注意,通过在函数内指定Verbose的默认值,您可以控制是否打印信息.
In[5]:= func1[arg_, opts___] := Module[{verbose},
verbose = Verbose /. {opts} /. {Verbose -> True};
If[verbose, Print["Verbosing function1: arg is ", arg]];
arg
];
func2[arg_, opts___] := Module[{verbose},
verbose = Verbose /. {opts} /. {Verbose -> False};
func1[arg, Verbose -> verbose]
];
In[7]:= func1[123]
During evaluation of In[7]:= Verbosing function1: arg is 123
Out[7]= 123
In[8]:= func2[456]
Out[8]= 456
In[9]:= func1[123, Verbose -> False]
Out[9]= 123
In[10]:= func2[456, Verbose -> True]
During evaluation of In[10]:= Verbosing function1: arg is 456
Out[10]= 456
Run Code Online (Sandbox Code Playgroud)
当然,可以详细说明这个例子符合Mathematica的编程标准(例如添加Options[func1, Verbose -> ...]标题然后从函数内部访问Options,但这不是重点.
| 归档时间: |
|
| 查看次数: |
1643 次 |
| 最近记录: |