简体   繁体   English

为`traceback.format_exc()`构建快捷方式

[英]Build shortcut for `traceback.format_exc()`

So I use traceback.format_exc() like this:所以我像这样使用traceback.format_exc()

try:
   # Some code
except:
   traceback_msg = '%s' % traceback.format_exc()
   print(traceback_msg)
   # Doing some stuff with it

pretty often in my code to output it to an additional file/stream and by writing code I am tired to keep typing it.经常在我的代码中到 output 它到一个额外的文件/流,通过编写代码我厌倦了继续输入它。 Is there a simple way to define a global shortcut/ExceptionHandler which keeps care and is easy to call from various places?有没有一种简单的方法来定义一个全局快捷方式/异常处理程序,它可以保持关注并且易于从各个地方调用?

You could use a module in a directory PYTHONPATH that imports under a shortened name (and itself has a short name).您可以使用目录PYTHONPATH中的模块,该模块以缩短的名称(并且本身具有短名称)导入。

In your setup script set environment variable PYTHONPATH to point to a directory, eg in .bashrc in Linux, put在你的设置脚本中设置环境变量PYTHONPATH指向一个目录,例如在 Linux 的.bashrc中,把

export PYTHONPATH=/path/to/my_dir:$PYTHONPATH

(You might want to do a test if any value already exists, and if not, suppress the colon here, but it's not critical.) (如果任何值已经存在,您可能想要进行测试,如果不存在,请在此处取消冒号,但这并不重要。)

and also create /path/to/my_dir/tb.py containing并创建/path/to/my_dir/tb.py包含

from traceback import format_exec as fe

Then you could do interactively eg:然后你可以交互地做,例如:

>>> import tb
>>> try:
...    a = 1 / 0
... except:
...    msg = tb.fe()
...    print(">>>", msg)

to give给予

>>> Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

Bear in mind though that your tb.py could conflict with another module also called tb.py that you are trying to use.请记住,尽管您的tb.py可能与您尝试使用的另一个名为tb.py的模块发生冲突。 Maybe for safety don't set PYTHONPATH all the time, but then (again Linux example here), set up an alias in your .bashrc .也许为了安全起见,不要一直设置PYTHONPATH ,但是(再次以 Linux 为例),在你的.bashrc中设置一个别名。

alias p='env PYTHONPATH=/path/to/my_dir:$PYTHONPATH python'

so that it is only set when you launch python with the p alias.以便仅在您使用p别名启动 python 时设置它。

There is also an environment variable PYTHONSTARTUP which you can point at a script that runs whenever you start python, although not used in this example.还有一个环境变量PYTHONSTARTUP ,您可以将其指向一个脚本,该脚本在您启动 python 时运行,尽管在此示例中未使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM