如何获取正在运行的 Python 脚本的名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1450478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the name of a running Python script?
提问by tehryan
How do I get the name of a running Python script?
如何获取正在运行的 Python 脚本的名称?
I tried os.__file__
but that returns the name of the file where os
resides.
我试过了,os.__file__
但这会返回os
所在文件的名称。
回答by Michael Foukarakis
>> import os
>> import sys
>> print sys.argv[0]
or if you just want the script and not the full path
或者如果您只想要脚本而不是完整路径
>>
>> print os.path.basename(sys.argv[0])
回答by Charles Ritchie
Use
利用
thisFile = __file__
It's magic!
这是魔法!
回答by John Machin
It depends on what you mean by "a running python script".
这取决于您所说的“正在运行的 python 脚本”是什么意思。
__file__
will give you the name of the currently executing file. If that's a module, you'll get where it was imported from e.g. blahblah.pyc
__file__
将为您提供当前正在执行的文件的名称。如果这是一个模块,你会得到它从例如 blahblah.pyc 导入的位置
sys.argv[0]
will give you the name of the script that is being run, even if called from a module that that script imported.
sys.argv[0]
将为您提供正在运行的脚本的名称,即使是从该脚本导入的模块中调用的。
Please do look up the answers to the earlier question on this topic (see S.Lott's comment on your question).
请务必查找有关此主题的先前问题的答案(请参阅 S.Lott 对您的问题的评论)。
回答by chitraxi raj
import __main__
print __main__.__file__
This will print the current filename which is running
这将打印正在运行的当前文件名
回答by Taylor Leese
sys.argv[0]
should give you the name of the script.
sys.argv[0]
应该给你脚本的名称。
回答by Dave
sys.path[0]
returns the path of the script that launched the Python interpreter.
返回启动 Python 解释器的脚本的路径。
If you read this script directly, it will return the path of the script. If the script was imported from another script, it will return the path of that script.
如果你直接阅读这个脚本,它会返回脚本的路径。如果脚本是从另一个脚本导入的,它将返回该脚本的路径。