简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM