Function to return the source code name itself in python

4

Is there any function to return the source file name itself?

The intent would be to create a log file, which one of the data would have the name of the source that is generating that log. If you have an error, it is easier to go directly to the source file for maintenance.

    
asked by anonymous 08.05.2018 / 16:30

1 answer

6

Just use __file__ .

For example:

print(__file__)

It is also possible to import the module sys and get through it the first execution argument, which is always the name of the file.

For example:

import sys
print(sys.argv[0])

You can use os.path.basename to get only the relative name of the directory. This prevents you from having to use split and validate which side of the bar (since in Windows the bar is opposite of * nix systems).

import os
print(os.path.basename(__file__))
    
08.05.2018 / 16:46