Collect name of file used

Asked

Viewed 56 times

0

I’m concluding a code that uses a lot of function copy of shutil. As I will distribute the file in executable format later and probably at some point will change its name, I want to know if there is a way to collect the name of the file where the script is being run. Something like:

nome = os.getbasename()
print(nome)
-globancy.exe

2 answers

0

You actually have several options. Of these I present to you three:

import os    
print(os.path.basename(__file__))

import sys
print (sys.argv[0])]

print (__file__)

There is a discussion interesting in the OS regarding the pros and cons of the use of each one. Worth consulting.

Where:

__file__ is the name of the file path from which the module was loaded, if it was loaded from a file. The __file__attribute can be missing for certain types of modules such as C modules that are statically linked to the interpreter; for extension modules dynamically loaded from a shared library, is the path name of shared library file.

  • sys.argv[0](requires import sys) is the name of the script that was called from the command line and can be an absolute path as per detailed in official documentation:

argv[0] is the name of the script (depends on the operating system if this is a path name or not). If the command was executed using the option -c command line for the interpreter, argv[0] will be set to the string '-c'. If no script name has been passed to the python interpreter, argv[0] is the empty string.

The information that made up this reply was removed from here. I thank the user Yoel.

0

Interpreting your question as "Discovering the name of the current Python script".

Thus, some solutions follow according to issue in English:

The attribute __file__ in any file will give you the way to this one. So if you want to skip the rest of the way, use os.path.basename(__file__).2 3

In the meantime, you can still import __main__ and use the same attribute __file__.4

Or else sys.argv[0], but remember to use equally os.path.basename if you only want the file name.5

and sys are modules and should be imported to be used.

Browser other questions tagged

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