使用Python获取当前脚本的名称

时间:2022-06-15 11:12:09

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

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

For example, I have a script called foo.py and I would like to do something like this inside it:

例如,我有一个名为foo的脚本。py和我想在里面做这样的事情:

print Scriptname

and get: foo.py.

并获得:foo.py。

11 个解决方案

#1


360  

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

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

#2


93  

import sys
print sys.argv[0]

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

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

#3


45  

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中不工作,因此使用上面提到的导入-as语法使其具有可移植性。

#4


33  

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])

#5


30  

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__是当前正在执行的文件,如官方文档所述:

    __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 C modules 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.

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

    From Python3.4 onwards, 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 -m command line option) using a relative path.

    从Python3.4开始,每个问题18416,__file__始终是绝对路径,除非当前执行的文件是一个使用相对路径直接执行的脚本(不是通过带有-m命令行选项的解释器)。

  • __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.

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

  • 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:

    sys。argv[0](需要导入sys)是从命令行调用的脚本名称,可能是一个绝对路径,如官方文档所述:

    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.

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

    As mentioned in another answer to this question, Python scripts that were converted into stand-alone executable programs via tools such as py2exe or PyInstaller might 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 Python file within that executable).

    正如在这个问题的另一个答案中提到的,通过py2exe或PyInstaller等工具转换成独立可执行程序的Python脚本在使用这种方法(即sys)时可能不会显示所需的结果。argv[0]将保存可执行文件的名称,而不是该可执行文件中主Python文件的名称)。


os.path.basename() may be invoked on any of the above in order to extract the actual file name.

可以对上面的任何一个调用os.path.basename(),以便提取实际的文件名。

#6


6  

Try this:

试试这个:

print __file__

#7


5  

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

#8


3  

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]

will output foo

将输出foo

#9


3  

This worked for me with Python 3.6

这在Python 3.6中对我有用

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

#10


0  

My fast dirty solution:

我快肮脏的解决方案:

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

#11


0  

For modern Python versions, Path(__file__).name should be more idiomatic. Also, Path(__file__).stem gives you the script name without the .py extension.

对于现代Python版本,Path(__file__).name应该更符合习惯用法。同时,路径(__file__)。stem为您提供没有.py扩展名的脚本名称。

#1


360  

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

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

#2


93  

import sys
print sys.argv[0]

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

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

#3


45  

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中不工作,因此使用上面提到的导入-as语法使其具有可移植性。

#4


33  

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])

#5


30  

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__是当前正在执行的文件,如官方文档所述:

    __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 C modules 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.

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

    From Python3.4 onwards, 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 -m command line option) using a relative path.

    从Python3.4开始,每个问题18416,__file__始终是绝对路径,除非当前执行的文件是一个使用相对路径直接执行的脚本(不是通过带有-m命令行选项的解释器)。

  • __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.

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

  • 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:

    sys。argv[0](需要导入sys)是从命令行调用的脚本名称,可能是一个绝对路径,如官方文档所述:

    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.

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

    As mentioned in another answer to this question, Python scripts that were converted into stand-alone executable programs via tools such as py2exe or PyInstaller might 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 Python file within that executable).

    正如在这个问题的另一个答案中提到的,通过py2exe或PyInstaller等工具转换成独立可执行程序的Python脚本在使用这种方法(即sys)时可能不会显示所需的结果。argv[0]将保存可执行文件的名称,而不是该可执行文件中主Python文件的名称)。


os.path.basename() may be invoked on any of the above in order to extract the actual file name.

可以对上面的任何一个调用os.path.basename(),以便提取实际的文件名。

#6


6  

Try this:

试试这个:

print __file__

#7


5  

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

#8


3  

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]

will output foo

将输出foo

#9


3  

This worked for me with Python 3.6

这在Python 3.6中对我有用

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

#10


0  

My fast dirty solution:

我快肮脏的解决方案:

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

#11


0  

For modern Python versions, Path(__file__).name should be more idiomatic. Also, Path(__file__).stem gives you the script name without the .py extension.

对于现代Python版本,Path(__file__).name应该更符合习惯用法。同时,路径(__file__)。stem为您提供没有.py扩展名的脚本名称。