<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p>

<p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile" rel="noreferrer">execfile</a>:</p>

<ul>
<li><code>script_1.py</code> calls <code>script_2.py</code>. </li>
<li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li>
</ul>

<p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p>

<p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>

[{'answer_id': 50502, 'author': 'Blair Conrad', 'author_id': 1199, 'author_profile': 'https://Stackoverflow.com/users/1199', 'pm_score': 4, 'selected': False, 'text': '<p>It\'s not entirely clear what you mean by "the filepath of the file that is currently running within the process".\n<code>sys.argv[0]</code> usually contains the location of the script that was invoked by the Python interpreter.\nCheck the <a href="https://docs.python.org/2/library/sys.html" rel="noreferrer">sys documentation</a> for more details.</p>\n\n<p>As @Tim and @Pat Notz have pointed out, the __file__ attribute provides access to</p>\n\n<blockquote>\n  <p>the file from which the module was\n  loaded, if it was loaded from a file</p>\n</blockquote>\n'}, {'answer_id': 50505, 'author': 'Pat Notz', 'author_id': 825, 'author_profile': 'https://Stackoverflow.com/users/825', 'pm_score': 3, 'selected': False, 'text': '<p>I think it\'s just <code>__file__</code>   Sounds like you may also want to checkout the <a href="https://docs.python.org/2/library/inspect.html" rel="nofollow noreferrer">inspect module</a>.</p>\n'}, {'answer_id': 50521, 'author': 'readonly', 'author_id': 4883, 'author_profile': 'https://Stackoverflow.com/users/4883', 'pm_score': 3, 'selected': False, 'text': '<p>The <code>__file__</code> attribute works for both the file containing the main execution code as well as imported modules.</p>\n\n<p>See <a href="https://web.archive.org/web/20090918095828/http://pyref.infogami.com/__file__" rel="nofollow noreferrer">https://web.archive.org/web/20090918095828/http://pyref.infogami.com/__file__</a></p>\n'}, {'answer_id': 50905, 'author': 'Pat Notz', 'author_id': 825, 'author_profile': 'https://Stackoverflow.com/users/825', 'pm_score': 9, 'selected': True, 'text': '<p>p1.py:</p>\n<pre><code>execfile(&quot;p2.py&quot;)\n</code></pre>\n<p>p2.py:</p>\n<pre><code>import inspect, os\nprint (inspect.getfile(inspect.currentframe())) # script filename (usually with path)\nprint (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) # script directory\n</code></pre>\n'}, {'answer_id': 50986, 'author': 'PabloG', 'author_id': 394, 'author_profile': 'https://Stackoverflow.com/users/394', 'pm_score': 2, 'selected': False, 'text': "<p>You can use <code>inspect.stack()</code></p>\n\n<pre><code>import inspect,os\ninspect.stack()[0]  =&gt; (&lt;frame object at 0x00AC2AC0&gt;, 'g:\\\\Python\\\\Test\\\\_GetCurrentProgram.py', 15, '&lt;module&gt;', ['print inspect.stack()[0]\\n'], 0)\nos.path.abspath (inspect.stack()[0][1]) =&gt; 'g:\\\\Python\\\\Test\\\\_GetCurrentProgram.py'\n</code></pre>\n"}, {'answer_id': 1955163, 'author': 'user13993', 'author_id': 13993, 'author_profile': 'https://Stackoverflow.com/users/13993', 'pm_score': 9, 'selected': False, 'text': '<pre><code>__file__\n</code></pre>\n\n<p>as others have said. You may also want to use <a href="https://docs.python.org/3/library/os.path.html#os.path.realpath" rel="noreferrer">os.path.realpath</a> to eliminate symlinks:</p>\n\n<pre><code>import os\n\nos.path.realpath(__file__)\n</code></pre>\n'}, {'answer_id': 1992378, 'author': 'appusajeev', 'author_id': 242382, 'author_profile': 'https://Stackoverflow.com/users/242382', 'pm_score': 3, 'selected': False, 'text': '<pre><code>import sys\n\nprint sys.path[0]\n</code></pre>\n\n<p>this would print the path of the currently executing script</p>\n'}, {'answer_id': 2345265, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': "<p>The suggestions marked as best are all true if your script consists of only one file. </p>\n\n<p>If you want to find out the name of the executable (i.e. the root file passed to the python interpreter for the current program) from a file that may be imported as a module, you need to do this (let's assume this is in a file named <em>foo.py</em>):</p>\n\n<p><code>import inspect</code></p>\n\n<p><code>print inspect.stack()[-1][1]</code></p>\n\n<p>Because the last thing (<code>[-1]</code>) on the stack is the first thing that went into it (stacks are LIFO/FILO data structures).</p>\n\n<p>Then in file <em>bar.py</em> if you <code>import foo</code> it'll print <em>bar.py</em>, rather than <em>foo.py</em>, which would be the value of all of these:</p>\n\n<ul>\n<li><code>__file__</code></li>\n<li><code>inspect.getfile(inspect.currentframe())</code></li>\n<li><code>inspect.stack()[0][1]</code></li>\n</ul>\n"}, {'answer_id': 2665888, 'author': 'WBAR', 'author_id': 320104, 'author_profile': 'https://Stackoverflow.com/users/320104', 'pm_score': 2, 'selected': False, 'text': '<pre><code>import sys\nprint sys.argv[0]\n</code></pre>\n'}, {'answer_id': 5152554, 'author': 'mik80', 'author_id': 224642, 'author_profile': 'https://Stackoverflow.com/users/224642', 'pm_score': 0, 'selected': False, 'text': '<p>I used the approach with __file__<br>\n<code>os.path.abspath(__file__)</code><br>\nbut there is a little trick, it returns the .py file \nwhen the code is run the first time, \nnext runs give the name of *.pyc file<br>\nso I stayed with:<br>\n<code>inspect.getfile(inspect.currentframe())</code><br>\nor<br>\n<code>sys._getframe().f_code.co_filename</code>  </p>\n'}, {'answer_id': 6628348, 'author': 'Usagi', 'author_id': 313087, 'author_profile': 'https://Stackoverflow.com/users/313087', 'pm_score': 6, 'selected': False, 'text': '<p>I think this is cleaner:</p>\n\n<pre><code>import inspect\nprint inspect.stack()[0][1]\n</code></pre>\n\n<p>and gets the same information as:</p>\n\n<pre><code>print inspect.getfile(inspect.currentframe())\n</code></pre>\n\n<p>Where [0] is the current frame in the stack (top of stack) and [1] is for the file name, increase to go backwards in the stack i.e.</p>\n\n<pre><code>print inspect.stack()[1][1]\n</code></pre>\n\n<p>would be the file name of the script that called the current frame. Also, using [-1] will get you to the bottom of the stack, the original calling script.</p>\n'}, {'answer_id': 11861785, 'author': 'garmoncheg', 'author_id': 809092, 'author_profile': 'https://Stackoverflow.com/users/809092', 'pm_score': 4, 'selected': False, 'text': "<p>I have a script that must work under windows environment.\nThis code snipped is what I've finished with:</p>\n\n<pre><code>import os,sys\nPROJECT_PATH = os.path.abspath(os.path.split(sys.argv[0])[0])\n</code></pre>\n\n<p>it's quite a hacky decision. But it requires no external libraries and it's the most important thing in my case.</p>\n"}, {'answer_id': 18168345, 'author': 'vishal ekhe', 'author_id': 2068502, 'author_profile': 'https://Stackoverflow.com/users/2068502', 'pm_score': 4, 'selected': False, 'text': '<pre><code>import os\nprint os.path.basename(__file__)\n</code></pre>\n\n<p>this will give us the filename only. i.e. if abspath of file is c:\\abcd\\abc.py then 2nd line will print abc.py</p>\n'}, {'answer_id': 24390114, 'author': 'Kwuite', 'author_id': 3123191, 'author_profile': 'https://Stackoverflow.com/users/3123191', 'pm_score': 3, 'selected': False, 'text': '<pre><code>import os\nos.path.dirname(os.path.abspath(__file__))\n</code></pre>\n\n<p>No need for inspect or any other library.</p>\n\n<p>This worked for me when I had to import a script (from a different directory then the executed script), that used a configuration file residing in the same folder as the imported script.</p>\n'}, {'answer_id': 28356929, 'author': 'Neal Xiong', 'author_id': 1316480, 'author_profile': 'https://Stackoverflow.com/users/1316480', 'pm_score': 6, 'selected': False, 'text': '<pre><code>import os\nos.path.dirname(__file__) # relative directory path\nos.path.abspath(__file__) # absolute file path\nos.path.basename(__file__) # the file name only\n</code></pre>\n'}, {'answer_id': 30831888, 'author': 'Jahid', 'author_id': 3744681, 'author_profile': 'https://Stackoverflow.com/users/3744681', 'pm_score': 2, 'selected': False, 'text': '<p>This should work:</p>\n\n<pre><code>import os,sys\nfilename=os.path.basename(os.path.realpath(sys.argv[0]))\ndirname=os.path.dirname(os.path.realpath(sys.argv[0]))\n</code></pre>\n'}, {'answer_id': 31867043, 'author': 'Brian Burns', 'author_id': 243392, 'author_profile': 'https://Stackoverflow.com/users/243392', 'pm_score': 7, 'selected': False, 'text': '<p><strong>Update 2018-11-28:</strong></p>\n\n<p>Here is a summary of experiments with Python 2 and 3. With </p>\n\n<p>main.py - runs foo.py<br>\nfoo.py - runs lib/bar.py<br>\nlib/bar.py - prints filepath expressions  </p>\n\n<pre class="lang-none prettyprint-override"><code>| Python | Run statement       | Filepath expression                    |\n|--------+---------------------+----------------------------------------|\n|      2 | execfile            | os.path.abspath(inspect.stack()[0][1]) |\n|      2 | from lib import bar | __file__                               |\n|      3 | exec                | (wasn\'t able to obtain it)             |\n|      3 | import lib.bar      | __file__                               |\n</code></pre>\n\n<p>For Python 2, it might be clearer to switch to packages so can use <code>from lib import bar</code> - just add empty <code>__init__.py</code> files to the two folders.</p>\n\n<p>For Python 3, <code>execfile</code> doesn\'t exist - the nearest alternative is <code>exec(open(&lt;filename&gt;).read())</code>, though this affects the stack frames. It\'s simplest to just use <code>import foo</code> and <code>import lib.bar</code> - no <code>__init__.py</code> files needed.</p>\n\n<p>See also <a href="https://stackoverflow.com/questions/27517003/difference-between-import-and-execfile">Difference between import and execfile</a></p>\n\n<hr>\n\n<p><strong>Original Answer:</strong></p>\n\n<p>Here is an experiment based on the answers in this thread - with Python 2.7.10 on Windows.</p>\n\n<p><strong>The stack-based ones are the only ones that seem to give reliable results. The last two have the shortest syntax</strong>, i.e. -</p>\n\n<pre><code>print os.path.abspath(inspect.stack()[0][1])                   # C:\\filepaths\\lib\\bar.py\nprint os.path.dirname(os.path.abspath(inspect.stack()[0][1]))  # C:\\filepaths\\lib\n</code></pre>\n\n<p>Here\'s to these being added to <strong>sys</strong> as functions! Credit to @Usagi and @pablog</p>\n\n<p>Based on the following three files, and running main.py from its folder with <code>python main.py</code> (also tried execfiles with absolute paths and calling from a separate folder). </p>\n\n<p>C:\\filepaths\\main.py: <code>execfile(\'foo.py\')</code><br>\nC:\\filepaths\\foo.py: <code>execfile(\'lib/bar.py\')</code><br>\nC:\\filepaths\\lib\\bar.py:</p>\n\n<pre><code>import sys\nimport os\nimport inspect\n\nprint "Python " + sys.version\nprint\n\nprint __file__                                        # main.py\nprint sys.argv[0]                                     # main.py\nprint inspect.stack()[0][1]                           # lib/bar.py\nprint sys.path[0]                                     # C:\\filepaths\nprint\n\nprint os.path.realpath(__file__)                      # C:\\filepaths\\main.py\nprint os.path.abspath(__file__)                       # C:\\filepaths\\main.py\nprint os.path.basename(__file__)                      # main.py\nprint os.path.basename(os.path.realpath(sys.argv[0])) # main.py\nprint\n\nprint sys.path[0]                                     # C:\\filepaths\nprint os.path.abspath(os.path.split(sys.argv[0])[0])  # C:\\filepaths\nprint os.path.dirname(os.path.abspath(__file__))      # C:\\filepaths\nprint os.path.dirname(os.path.realpath(sys.argv[0]))  # C:\\filepaths\nprint os.path.dirname(__file__)                       # (empty string)\nprint\n\nprint inspect.getfile(inspect.currentframe())         # lib/bar.py\n\nprint os.path.abspath(inspect.getfile(inspect.currentframe())) # C:\\filepaths\\lib\\bar.py\nprint os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # C:\\filepaths\\lib\nprint\n\nprint os.path.abspath(inspect.stack()[0][1])          # C:\\filepaths\\lib\\bar.py\nprint os.path.dirname(os.path.abspath(inspect.stack()[0][1]))  # C:\\filepaths\\lib\nprint\n</code></pre>\n'}, {'answer_id': 37815779, 'author': 'hayj', 'author_id': 3406616, 'author_profile': 'https://Stackoverflow.com/users/3406616', 'pm_score': 0, 'selected': False, 'text': '<p>I wrote a function which take into account eclipse <strong>debugger</strong> and <strong>unittest</strong>.\nIt return the folder of the first script you launch. You can optionally specify the <em>__file__</em> var, but the main thing is that you don\'t have to share this variable across all your <strong>calling hierarchy</strong>.</p>\n\n<p>Maybe you can handle others stack particular cases I didn\'t see, but for me it\'s ok.</p>\n\n<pre><code>import inspect, os\ndef getRootDirectory(_file_=None):\n    """\n    Get the directory of the root execution file\n    Can help: http://stackoverflow.com/questions/50499/how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing\n    For eclipse user with unittest or debugger, the function search for the correct folder in the stack\n    You can pass __file__ (with 4 underscores) if you want the caller directory\n    """\n    # If we don\'t have the __file__ :\n    if _file_ is None:\n        # We get the last :\n        rootFile = inspect.stack()[-1][1]\n        folder = os.path.abspath(rootFile)\n        # If we use unittest :\n        if ("/pysrc" in folder) &amp; ("org.python.pydev" in folder):\n            previous = None\n            # We search from left to right the case.py :\n            for el in inspect.stack():\n                currentFile = os.path.abspath(el[1])\n                if ("unittest/case.py" in currentFile) | ("org.python.pydev" in currentFile):\n                    break\n                previous = currentFile\n            folder = previous\n        # We return the folder :\n        return os.path.dirname(folder)\n    else:\n        # We return the folder according to specified __file__ :\n        return os.path.dirname(os.path.realpath(_file_))\n</code></pre>\n'}, {'answer_id': 43890336, 'author': 'pbaranski', 'author_id': 1266040, 'author_profile': 'https://Stackoverflow.com/users/1266040', 'pm_score': 1, 'selected': False, 'text': '<p>To get directory of executing script  </p>\n\n<pre><code> print os.path.dirname( inspect.getfile(inspect.currentframe()))\n</code></pre>\n'}, {'answer_id': 50760702, 'author': 'Lucas Azevedo', 'author_id': 4075155, 'author_profile': 'https://Stackoverflow.com/users/4075155', 'pm_score': 0, 'selected': False, 'text': "<p>Simplest way is:</p>\n\n<p>in <strong>script_1.py:</strong></p>\n\n<pre><code>import subprocess\nsubprocess.call(['python3',&lt;path_to_script_2.py&gt;])\n</code></pre>\n\n<p>in <strong>script_2.py:</strong></p>\n\n<pre><code>sys.argv[0]\n</code></pre>\n\n<p>P.S.: I've tried <code>execfile</code>, but since it reads script_2.py as a string, <code>sys.argv[0]</code> returned <code>&lt;string&gt;</code>.</p>\n"}, {'answer_id': 54832312, 'author': 'Soumyajit', 'author_id': 6692537, 'author_profile': 'https://Stackoverflow.com/users/6692537', 'pm_score': 3, 'selected': False, 'text': '<p>Try this,</p>\n\n<pre><code>import os\nos.path.dirname(os.path.realpath(__file__))\n</code></pre>\n'}, {'answer_id': 55988112, 'author': 'BaiJiFeiLong', 'author_id': 5254103, 'author_profile': 'https://Stackoverflow.com/users/5254103', 'pm_score': 2, 'selected': False, 'text': '<pre><code>print(__file__)\nprint(__import__("pathlib").Path(__file__).parent)\n</code></pre>\n'}, {'answer_id': 56799977, 'author': 'craymichael', 'author_id': 6557588, 'author_profile': 'https://Stackoverflow.com/users/6557588', 'pm_score': 2, 'selected': False, 'text': '<p>Here is what I use so I can throw my code anywhere without issue. <code>__name__</code> is always defined, but <code>__file__</code> is only defined when the code is run as a file (e.g. not in IDLE/iPython).</p>\n<pre class="lang-py prettyprint-override"><code>if \'__file__\' in globals():\n    self_name = globals()[\'__file__\']\nelif \'__file__\' in locals():\n    self_name = locals()[\'__file__\']\nelse:\n    self_name = __name__\n</code></pre>\n<p>Alternatively, this can be written as:</p>\n<pre class="lang-py prettyprint-override"><code>self_name = globals().get(\'__file__\', locals().get(\'__file__\', __name__))\n</code></pre>\n'}, {'answer_id': 57631907, 'author': 'Doug', 'author_id': 1494503, 'author_profile': 'https://Stackoverflow.com/users/1494503', 'pm_score': 4, 'selected': False, 'text': '<p>Since Python 3 is fairly mainstream, I wanted to include a <code>pathlib</code> answer, as I believe that it is probably now a better tool for accessing file and path information.</p>\n\n<pre><code>from pathlib import Path\n\ncurrent_file: Path = Path(__file__).resolve()\n</code></pre>\n\n<p>If you are seeking the directory of the current file, it is as easy as adding <code>.parent</code> to the <code>Path()</code> statement:</p>\n\n<pre><code>current_path: Path = Path(__file__).parent.resolve()\n</code></pre>\n'}, {'answer_id': 70773078, 'author': 'nichoio', 'author_id': 6312338, 'author_profile': 'https://Stackoverflow.com/users/6312338', 'pm_score': 0, 'selected': False, 'text': '<p>The following returns the path where your current main script is located at. I tested this with Linux, Win10, IPython and Jupyter Lab. I needed a solution that works for local Jupyter notebooks as well.</p>\n<pre><code>import builtins\nimport os\nimport sys\n\ndef current_dir():\n    if &quot;get_ipython&quot; in globals() or &quot;get_ipython&quot; in dir(builtins):\n        # os.getcwd() is PROBABLY the dir that hosts the active notebook script.\n        # See also https://github.com/ipython/ipython/issues/10123\n        return os.getcwd()\n    else:\n        return os.path.abspath(os.path.dirname(sys.argv[0]))\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/50499', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4872/']