Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the "current" source file in Python 3?

What's the simplest way to find the path to the file in which I am "executing" some code? By this, I mean that if I have a file foo.py that contains:

print(here())

I would like to see /some/path/foo.py (I realise that in practice what file is "being executed" is complicated, but I think the above is well defined - a source file that contains some function that, when executed, gives the path to said file).

I have needed this in the past to make tests (that require some external file) self-contained, and I am currently wondering if it would be a useful way to locate some support files needed by a program. But I have never found a good way of doing this. The inspect module sounds like it should work, but you seem to need a class or function that is defined in that module.

In particular, the module instances contain __file__ attributes, but I can't see how to get the "current" module. Objects have a __module__ attribute, but that's the module name, not a module instance.

I guess one way is to throw and catch an exception and inspect the contents, but that seems like hard work. Surely there is a simple, easy way that I have missed?

like image 458
andrew cooke Avatar asked Aug 22 '12 00:08

andrew cooke


People also ask

How do I get the current 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.

What is __ file __ in Python?

__file__ is a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module. The updating and maintaining of this variable is the responsibility of the import system.

How do I get the current script name?

For getting the name of the Python script that is currently running you can use __file__. And if you want to remove the directory part which might be present with the name of the script, you can use os. path. basename(__file__).

What is source file in Python?

Python source files are files that contain Python source code. As Python can be used as a scripting language, Python source files can be considered as scripts.


1 Answers

To get the absolute path of the current file:

import os
os.path.abspath(__file__)
like image 51
Brian Ustas Avatar answered Sep 21 '22 00:09

Brian Ustas