【问题标题】:How do I set the filename of a module in Python so that exceptions that occur in the module use that filename?如何在 Python 中设置模块的文件名,以便模块中发生的异常使用该文件名?
【发布时间】:2012-10-19 15:30:14
【问题描述】:

我正在使用 imp 库从字符串中导入模块(不要问)。这一切都很好,花花公子,但是当这样的模块出现错误时,我会得到这样的堆栈跟踪:

Traceback (most recent call last):
  File "<string>", line 33, in do_something
  File "<string>", line 20, in really_do_something
Exception: STRING FILENAME EXAMPLE

我尝试将模块上的 file 属性设置为有意义的值,但在异常回溯中仍使用 &lt;string&gt; 文件名。

关于如何指定异常中使用的文件名有什么想法吗?

更新:我正在像这样使用 imp:Dynamic module importing is trying to do relative imports when it shouldn't

【问题讨论】:

  • 你能显示你使用imp导入模块的代码吗?
  • 文件名取自代码对象,而不是模块对象。我们需要看看你是如何编译字符串的。
  • k,添加了我如何使用 imp 模块的链接
  • 看起来imp.new_module 返回了一个新的(空)模块。然后用exec 填充它。重新处理逻辑似乎更容易,以便改用imp.load_module...

标签: python string python-import python-module


【解决方案1】:

文件名在exec() 生成的代码对象中设置。不要将exec() 与字符串一起使用,而应使用compile() 单独编译代码。这样你就可以设置文件名了:

code = compile(file_contents, '/your/filename.py', 'exec')
exec(code, mod.__dict__)

【讨论】:

  • vars(mod) 是mod.__dict__ 的替代品。
猜你喜欢
  • 1970-01-01
  • 2010-10-11
  • 1970-01-01
  • 2010-10-08
  • 2011-08-05
  • 2013-08-22
  • 2017-12-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多