mklauber
mklauber

Reputation: 1144

Is there a way to tell when a python file is loaded using PYTHONSTARTUP vs. being run as a script?

All, I recently discovered the PYTHONSTARTUP environment variable, and am looking forward to setting up several of my utility functions to automatically load into my interpreter. However, one thing I'd like to be able to do is use the same script to setup the environment variable itself.

My issue is determining when the file is run as a script. My thought was to use the if __name__ == "__main__": trick to determine when the file was run as a script, but testing showed that when the file is loaded via PYTHONSTARTUP the name shows as "__main__".

Does anyone know of a way to identify when a file is run as a script vs. when it is loaded via PYTHONSTARTUP?

Upvotes: 1

Views: 340

Answers (2)

mklauber
mklauber

Reputation: 1144

Found a better solution:

if sys.argv[0] == __file__:
    print "It works!"

Basically, because the name of the file is always the first argument in argv[] we just check if argv[0] is the same as the __file__, which is only true when the file was opened as a script.

Upvotes: 1

Lennart Regebro
Lennart Regebro

Reputation: 172249

You could check if the PYTHONSTARTUP environment variable is set to the current filename (via __file__).

 import os
 if os.environ.get('PYTHONSTARTUP') == __file__:
     print "Used as startup!"

Worked fine for me.

Upvotes: 3

Related Questions