我可以用什么方法代替 python 中的 __file__?

问题描述 投票:0回答:3

我用 cython 将我的 python 代码转换为 c,然后编译 .c 文件并在我的项目中使用 .so。 我的问题: 我在我的 python 代码中使用

__file__
并且在通过 gcc 编译时,它没有出错。但是当我运行程序并在其他 python 文件中导入 .so 时,从
__file__
行出现错误。

如何解决这个问题?有什么方法可以用

__file__
代替吗?

python cython
3个回答
13
投票

尝试在文件开头添加:

import inspect
import sys
if not hasattr(sys.modules[__name__], '__file__'):
    __file__ = inspect.getfile(inspect.currentframe())

0
投票

不太确定如何使它与 python 兼容,但 gcc

#define
s
__FILE__
作为代码所在文件的名称。


0
投票

为什么不使用

sys.argv[0]

即使将它编译成 cython 可执行文件,它也能正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.