Finding name of running script

R

runes

Is it a more pythonic way of finding the name of the running script
than these?

from os import sep
from sys import argv

print argv[0].split(sep)[-1]
# or
print locals()['__file__'].split(sep)[-1]
# or
print globals()['__file__'].split(sep)[-1]
 
M

M.E.Farmer

print locals()['__file__'].split(sep)[-1]
..split(sep)[-1] is pretty dense reading.
try:
print os.basename(locals()['__file__'])
Is it a more pythonic way of finding the name of the running script
than these?

from os import sep
from sys import argv

print argv[0].split(sep)[-1]
# or
print locals()['__file__'].split(sep)[-1]
# or
print globals()['__file__'].split(sep)[-1]

M.E.Farmer
 
R

runes

Thanks!

That's os.path.basename() I guess. It's better, but still complex.

I have a
_nof_ = argv[0].split(sep)[-1] in my script template and use it under
the usage() function to tell what the script does, like:

"cf.py counts files in directory or directory structure"

If I change the filename, I want it to be automatically reflected when
running the script. That's the motivation.

I have the feeling that I came a cross some very simple way to extract
the filename, but I can't find my mental note ;-)
 
M

M.E.Farmer

runes said:
Thanks!

That's os.path.basename() I guess. It's better, but still complex.

Yea murphy's typo ;)
I have a
_nof_ = argv[0].split(sep)[-1] in my script template and use it under
the usage() function to tell what the script does, like:
"cf.py counts files in directory or directory structure"

If I change the filename, I want it to be automatically reflected when
running the script. That's the motivation.

Generally I do it the very same way just spell it different.
os.path.basename(sys.argv[0])
I have the feeling that I came a cross some very simple way to extract
the filename, but I can't find my mental note ;-)
Maybe you found some black magic ;)
M.E.Farmer
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,234
Messages
2,571,180
Members
47,813
Latest member
RustyGary3

Latest Threads

Top