在 Python 中获取当前脚本的名称 [英] Get name of current script in Python
本文介绍了在 Python 中获取当前脚本的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试获取当前正在运行的 Python 脚本的名称.
I'm trying to get the name of the Python script that is currently running.
我有一个名为 foo.py
的脚本,我想做这样的事情来获取脚本名称:
I have a script called foo.py
and I'd like to do something like this in order to get the script name:
print Scriptname
推荐答案
您可以使用 __file__
获取当前文件的名称.在主模块中使用时,这是最初调用的脚本的名称.
You can use __file__
to get the name of the current file. When used in the main module, this is the name of the script that was originally invoked.
如果您想省略目录部分(可能存在),您可以使用 os.path.basename(__file__)
.
If you want to omit the directory part (which might be present), you can use os.path.basename(__file__)
.
这篇关于在 Python 中获取当前脚本的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文