13

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.

2

6 Answers 6

26
>> 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])
Sign up to request clarification or add additional context in comments.

Comments

25

Use

thisFile = __file__

It's magic!

4 Comments

I get NameError: name '__file__' is not defined.
Which Python implementation are you using? CPython or something else?
Python 2.7.3. I just ran "python" then print __file__.
@bos I don't think you can get it from interactive mode, need to be run as a file.
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).

Comments

1

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

Comments

1
import __main__
print __main__.__file__

This will print the current filename which is running

Comments

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

1 Comment

I didn't downvote, but just tested. This gave me K:/code/allRequirementsTests which is the absolute path of the script, minus the extension

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.