Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I'm trying to get the name of the Python script that is currently running.

For example, I have a script called foo.py and I would like to do something like this inside it:

print Scriptname

and get: foo.py.

2 Answers

0 votes
by (106k points)

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__).

Another thing you can use sys.argv[] and it will print foo.py for python foo.py, dir/foo.py for python dir/foo.py, etc.

import sys 

print(sys.argv[0])

image

0 votes
ago by (1.9k points)

This attribute with the os module could be used to get the name of the currently running Python script. Here's how you can do this: 

import os 

script_name = os.path.basename(__file__) 

print(script_name) 

Explanation:

 __file__ is a special variable holding the path to the script being executed. The function os.path.basename extracts just the filename from that path. If you run this code in a script like foo.py, the output will always be foo.py, regardless of where it was sourced or launched from. 

This is really useful when you want the name of the script for logging purposes but don't have it available while the script is actually running

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 18, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 11, 2019 in Java by Ritik (3.5k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...