Get name of current script in Python

99封情书 提交于 2019-12-17 05:23:21

问题


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

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

回答1:


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




回答2:


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




回答3:


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:

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.




回答4:


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

    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.

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

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

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


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.

From Python 3.4 onwards, per PEP 428, the PurePath class of the pathlib module may be used as well. Specifically, pathlib.PurePath().name extracts the actual file name and pathlib.PurePath().stem extracts the actual file name without its suffix.




回答5:


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



回答6:


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




回答7:


Try this:

print __file__



回答8:


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

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

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

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




回答9:


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

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



回答10:


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.




回答11:


Since the OP asked for the name of the current script file I would prefer

import os
os.path.split(sys.argv[0])[1]



回答12:


My fast dirty solution:

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



回答13:


os.path.abspath(__file__) will give you an absolute path (relpath() available as well).

sys.argv[-1] will give you a relative path.



来源:https://stackoverflow.com/questions/4152963/get-name-of-current-script-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!