如何在Python中设置模块的文件名,以便模块中出现的异常使用该文件名?

时间:2012-10-19 15:30:14

标签: python string python-import python-module

我正在使用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

我已尝试将模块上的文件属性设置为有意义的内容,但<string>文件名仍在异常回溯中使用。

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

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

1 个答案:

答案 0 :(得分:4)

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

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