在 Python 中获取当前脚本的名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4152963/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:30:10  来源:igfitidea点击:

Get name of current script in Python

pythonscriptingbasename

提问by SubniC

I'm trying to get the name of the Python script that is currently running.

我正在尝试获取当前正在运行的 Python 脚本的名称。

I have a script called foo.pyand I'd like to do something like this in order to get the script name:

我有一个名为的脚本foo.py,我想做这样的事情来获取脚本名称:

print Scriptname

采纳答案by Sven Marnach

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.

您可以使用__file__来获取当前文件的名称。在主模块中使用时,这是最初调用的脚本的名称。

If you want to omit the directory part (which might be present), you can use os.path.basename(__file__).

如果您想省略目录部分(可能存在),您可以使用os.path.basename(__file__).

回答by Chris Morgan

import sys
print sys.argv[0]

This will print foo.pyfor python foo.py, dir/foo.pyfor python dir/foo.py, etc. It's the first argument to python. (Note that after py2exe it would be foo.exe.)

这将打印foo.pyfor python foo.pydir/foo.pyforpython dir/foo.py等。它是 的第一个参数python。(请注意,在 py2exe 之后它将是foo.exe.)

回答by demas

Try this:

尝试这个:

print __file__

回答by Ambroz Bizjak

Note that __file__will give the file where this code resides, which can be imported and different from the main file being interpreted. To get the main file, the special __main__module can be used:

请注意,这__file__将给出此代码所在的文件,该文件可以导入并且与正在解释的主文件不同。要获取主文件,可以使用特殊的__main__模块:

import __main__ as main
print(main.__file__)

Note that __main__.__file__works in Python 2.7 but not in 3.2, so use the import-as syntax as above to make it portable.

请注意,它__main__.__file__在 Python 2.7 中有效,但在 3.2 中无效,因此请使用上述 import-as 语法使其可移植。

回答by Manoj Sahu

The Above answers are good . But I found this method more efficient using above results.
This results in actual script file name not a path.

上面的答案很好。但是我发现使用上述结果这种方法更有效。
这导致实际脚本文件名不是路径。

import sys    
import os    
file_name =  os.path.basename(sys.argv[0])

回答by Yoel

For completeness' sake, I thought it would be worthwhile summarizing the various possible outcomes and supplying references for the exact behaviour of each:

为了完整起见,我认为总结各种可能的结果并为每个结果的确切行为提供参考是值得的:

  • __file__is the currently executing file, as detailed in the official documentation:

    __file__is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__attribute may be missing for certain types of modules, such as Cmodules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

    From Python3.4onwards, per issue 18416, __file__is always an absolute path, unless the currently executing file is a script that has been executed directly (not via the interpreter with the -mcommand line option) using a relative path.

  • __main__.__file__(requires importing __main__) simply accesses the aforementioned __file__attribute of the main module, e.g. of the script that was invoked from the command line.

  • sys.argv[0](requires importing sys) is the script name that was invoked from the command line, and might be an absolute path, as detailed in the official documentation:

    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 -ccommand 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.

    As mentioned in another answer to this question, Pythonscripts that were converted into stand-alone executable programs via tools such as py2exeor PyInstallermight not display the desired result when using this approach (i.e. sys.argv[0]would hold the name of the executable rather than the name of the main Pythonfile within that executable).

  • If none of the aforementioned options seem to work, probably due to an irregular import operation, the inspect modulemight prove useful. In particular, invoking inspect.getfile(...)on inspect.currentframe()could work, although the latter would return Nonewhen running in an implementation without Pythonstack frame.

  • __file__是当前正在执行的文件,详见官方文档

    __file__是加载模块的文件的路径名,如果它是从文件加载的。__file__某些类型的模块可能缺少该属性,例如静态链接到解释器的C模块;对于从共享库动态加载的扩展模块,它是共享库文件的路径名。

    从Python3.4起,每发行18416__file__始终是一个绝对路径,除非当前正在执行的文件是已经被直接执行(不通过与解释脚本-m使用相对路径命令行选项)。

  • __main__.__file__(需要导入__main__)只需访问主模块的上述__file__属性,例如从命令行调用的脚本的属性。

  • sys.argv[0](requires importing sys) 是从命令行调用的脚本名称,可能是绝对路径,详见官方文档

    argv[0]是脚本名称(它是否为完整路径名取决于操作系统)。如果命令是使用-c解释器的命令行选项执行的,argv[0]则设置为字符串'-c'。如果没有脚本名称传递给 Python 解释器,argv[0]则为空字符串。

    正如提到的另一个回答这个问题Python的是被通过的工具,如转换成独立的可执行程序的脚本py2exePyInstaller可能不会显示预期的结果使用这种方法的时候(也就是sys.argv[0]将持有的可执行文件的名称,而不是名称该可执行文件中的主要Python文件)。

  • 如果上述选项似乎都不起作用,可能是由于不规则的导入操作,则检查模块可能会很有用。特别是,调用inspect.getfile(...)oninspect.currentframe()可以工作,尽管后者在没有Python堆栈帧的实现中运行时会返回None



Handling symbolic links

处理符号链接

If the current script is a symbolic link, then all of the above would return the path of the symbolic link rather than the path of the real file and os.path.realpath(...)should be invoked in order to extract the latter.

如果当前脚本是一个符号链接,那么上面所有的都将返回符号链接的路径而不是真实文件的路径,并且os.path.realpath(...)应该被调用以提取后者。



Further manipulations that extract the actual file name

提取实际文件名的进一步操作

os.path.basename(...)may be invoked on any of the above in order to extract the actual file name and os.path.splitext(...)may be invoked on the actual file name in order to truncate its suffix, as in os.path.splitext(os.path.basename(...)).

os.path.basename(...)可以在上述任何一个上调用以提取实际文件名,os.path.splitext(...)也可以在实际文件名上调用以截断其后缀,如os.path.splitext(os.path.basename(...)).

From Python 3.4onwards, per PEP 428, the PurePathclassof the pathlibmodulemay be used as well on any of the above. Specifically, pathlib.PurePath(...).nameextracts the actual file name and pathlib.PurePath(...).stemextracts the actual file name without its suffix.

Python的3.4起,每PEP 428中,PurePath的的pathlib模块可以用作以及任何上述的。具体来说,pathlib.PurePath(...).name提取实际文件名,pathlib.PurePath(...).stem提取不带后缀的实际文件名。

回答by Charlie OConor

The first argument in sys will be the current file name so this will work

sys 中的第一个参数将是当前文件名,因此这将起作用

   import sys
   print sys.argv[0] # will print the file name

回答by xtonousou

Note: If you are using Python 3+, then you should use the print() function instead

注意:如果您使用的是 Python 3+,那么您应该使用 print() 函数代替

Assuming that the filename is foo.py, the below snippet

假设文件名是foo.py,下面的代码片段

import sys
print sys.argv[0][:-3]

or

或者

import sys
print sys.argv[0][::-1][3:][::-1]

As for other extentions with more characters, for example the filename foo.pypy

至于其他具有更多字符的扩展名,例如文件名 foo.pypy

import sys
print sys.argv[0].split('.')[0]

If you want to extract from an absolute path

如果要从绝对路径中提取

import sys
print sys.argv[0].split('/')[-1].split('.')[0]

will output foo

会输出 foo

回答by E.Big

My fast dirty solution:

我的快速肮脏解决方案:

__file__.split('/')[-1:][0]

回答by Gajendra D Ambi

If you're doing an unusual import (e.g., it's an options file), try:

如果您正在执行不寻常的导入(例如,它是一个选项文件),请尝试:

import inspect
print (inspect.getfile(inspect.currentframe()))

Note that this will return the absolute path to the file.

请注意,这将返回文件的绝对路径。