从导入的模块中引用 __file__

refer to __file__ from imported module

我有一个主程序 main.py 导入了一个模块 lib.py

是否可以在 lib.py 中有一个变量,其中 return 是调用脚本的主程序的名称?我的意思是 return 如果 lib.py 直接是 运行 则为“lib.py”,如果 main.py 是 main.py 则为“main.py” 运行 并打电话给 lib.py

这里是lib.py

import os
print(os.path.basename(__file__))

如果我运行lib.py,那么输出就是我想要的,也就是

lib.py

这里是main.py

import lib
print(__file__)

输出为

lib.py
main.py

是否有一个我可以从 lib.py 调用的包含主程序名称的变量? 我想要输出

main.py
main.py

根据[Python.Docs]: sys.argv重点是我的):

The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.

因此,你应该使用sys.argv[0](不要忘记import sys 1st)。