Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
  • In turn, 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.)

like image 673
Ray Avatar asked Sep 08 '08 19:09

Ray


People also ask

How do I find the current file path?

Run it with the python (or python3 ) command. You can get the absolute path of the current working directory with os. getcwd() and the path specified with the python3 command with __file__ . In Python 3.8 and earlier, the path specified by the python (or python3 ) command is stored in __file__ .

How do I get the path of the current executed file in Python?

Method 1: Using os. The os. getcwd() method is used for getting the Current Working Directory in Python. The absolute path to the current working directory is returned in a string by this function of the Python OS module.

How it is possible to get path and filename of the given file?

A path may contain the drive name, directory name(s) and the filename. To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null.

How do I show the path of a file in Python?

In order to obtain the Current Working Directory in Python, use the os. getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.


2 Answers

__file__ 

as others have said. You may also want to use os.path.realpath to eliminate symlinks:

import os  os.path.realpath(__file__) 
like image 195
user13993 Avatar answered Sep 21 '22 22:09

user13993


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 
like image 32
Pat Notz Avatar answered Sep 21 '22 22:09

Pat Notz