How do I get the path and name of the file that is currently executing?
I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.
For example, let's say I have three files. Using execfile:
script_1.py
calls script_2.py
. script_2.py
calls script_3.py
. How can I get the file name and path of script_3.py
, from code within script_3.py
, without having to pass that information as arguments from script_2.py
?
(Executing os.getcwd()
returns the original starting script's filepath not the current file's.)
p1.py:
execfile("p2.py")
p2.py:
import inspect, os
print inspect.getfile(inspect.currentframe()) # script filename (usually with path)
print os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # script directory
__file__
as others have said. You may also want to use os.path.realpath to eliminate symlinks:
import os
os.path.realpath(__file__)
Here is an experiment based on the answers in this thread - with Python 2.7.10 on Windows.
The stack-based ones are the only ones that seem to give reliable results. The last two have the shortest syntax , ie -
print os.path.abspath(inspect.stack()[0][1]) # C:testpathlibscript3.py
print os.path.dirname(os.path.abspath(inspect.stack()[0][1])) # C:testpathlib
Here's to these being added to sys as functions! Credit to @Usagi and @pablog
Based on the following three files, and running script1.py from its folder with python script1.py
(also tried execfiles with absolute paths and calling from a separate folder).
C:testpathscript1.py: execfile('script2.py')
C:testpathscript2.py: execfile('lib/script3.py')
C:testpathlibscript3.py:
import sys
import os
import inspect
print "Python " + sys.version
print
print __file__ # script1.py
print sys.argv[0] # script1.py
print inspect.stack()[0][1] # lib/script3.py
print sys.path[0] # C:testpath
print
print os.path.realpath(__file__) # C:testpathscript1.py
print os.path.abspath(__file__) # C:testpathscript1.py
print os.path.basename(__file__) # script1.py
print os.path.basename(os.path.realpath(sys.argv[0])) # script1.py
print
print sys.path[0] # C:testpath
print os.path.abspath(os.path.split(sys.argv[0])[0]) # C:testpath
print os.path.dirname(os.path.abspath(__file__)) # C:testpath
print os.path.dirname(os.path.realpath(sys.argv[0])) # C:testpath
print os.path.dirname(__file__) # (empty string)
print
print inspect.getfile(inspect.currentframe()) # lib/script3.py
print os.path.abspath(inspect.getfile(inspect.currentframe())) # C:testpathlibscript3.py
print os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # C:testpathlib
print
print os.path.abspath(inspect.stack()[0][1]) # C:testpathlibscript3.py
print os.path.dirname(os.path.abspath(inspect.stack()[0][1])) # C:testpathlib
print
链接地址: http://www.djcxy.com/p/29028.html
上一篇: 寻找快速和完整的PowerShell教程