12

How do I get the name of a running Python script?

I tried os.__file__ but that returns the name of the file where os resides.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
tehryan
  • 24,405
  • 11
  • 28
  • 17
  • 2
    Duplicate: http://stackoverflow.com/questions/50499/in-python-how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing – S.Lott Sep 20 '09 at 11:46
  • http://stackoverflow.com/q/4152963/2336725 seems to be a better duplicate. – Teepeemm May 12 '14 at 22:27

6 Answers6

23
>> import os
>> import sys
>> print sys.argv[0]

or if you just want the script and not the full path

>>
>> print os.path.basename(sys.argv[0])
Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123
23

Use

thisFile = __file__

It's magic!

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Charles Ritchie
  • 2,283
  • 2
  • 16
  • 21
11

It depends on what you mean by "a running python script".

__file__ will give you the name of the currently executing file. If that's a module, you'll get where it was imported from e.g. blahblah.pyc

sys.argv[0] will give you the name of the script that is being run, even if called from a module that that script imported.

Please do look up the answers to the earlier question on this topic (see S.Lott's comment on your question).

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
John Machin
  • 81,303
  • 11
  • 141
  • 189
1

sys.argv[0] should give you the name of the script.

Taylor Leese
  • 51,004
  • 28
  • 112
  • 141
1
import __main__
print __main__.__file__

This will print the current filename which is running

chitraxi raj
  • 39
  • 1
  • 10
-1
sys.path[0]

returns the path of the script that launched the Python interpreter.

If you read this script directly, it will return the path of the script. If the script was imported from another script, it will return the path of that script.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Dave
  • 385
  • 1
  • 2