Function to return the proper python source code name

Asked

Viewed 181 times

4

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

The intention 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’s easier to go directly to the source file for maintenance.

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 argument of execution, which is always the file name.

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 using a split and validate which side of the bar (since in Windows the bar is on the opposite side of *Nix systems).

import os
print(os.path.basename(__file__))
  • In this case, it is taking the absolute path plus the file name. Would you know another function to return only the file name? Thank you!

  • @Rodrigosaito which case? I put two ways

  • In both cases, both show the absolute path plus the file name

  • Python 2 or 3? In my think I was showing only the final name even. Now I’m not in front of the PC, so I have no way to test. Anyway you can always split by / and catch the last position of the result.

  • It would be in python 3. Good idea. I will make a function to receive the function, give the split, check the size of the vector and return the last position. Thank you very much.

  • @Rodrigosaito I gave an even better suggestion in the answer. Btw, you can always mark an answer as correct in your questions. Just use the V on the left side of the response.

  • I am in no way belittling your reply and I thank you for that. I will actually complement your suggestion, as it will be used several times, which encapsulate all this in a function is better not to keep repeating code. Thank you

  • @Rodrigosaito Sure, I know you’re not belittling her. I just left the tip to complement the answer.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.