开发者

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

开发者 https://www.devze.com 2023-02-02 12:17 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消