MarcinKonowalczyk
MarcinKonowalczyk

Reputation: 2788

Python: Running a strip of code unless imported

I have a file that I'm importing into my program (say a file with dictionaries). At the beginning of this file I want to put a strip of code which prints that this is not the main file and then exit(). The problem I find is that this code is being run on import of the dictionaries module which I don't want happening. How to prevent that?

I tried this but it doesn't work:

if not Main_file:
    print('These aren\'t the droids you\'re looking for')
    exit()

in the main file there would of course be Main_file = True before import.

Upvotes: 0

Views: 88

Answers (2)

zhangyangyu
zhangyangyu

Reputation: 8610

if __name__ == '__main__' can identify whether this is the main file.

Upvotes: 1

mata
mata

Reputation: 69012

You can use the __name__ special variable to check if your module is used as main:

if __name__ == '__main__':
    print('These aren\'t the droids you\'re looking for')
    exit()

Upvotes: 3

Related Questions