0

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.

MarcinKonowalczyk
  • 2,577
  • 4
  • 20
  • 26

2 Answers2

3

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()
mata
  • 67,110
  • 10
  • 163
  • 162
1

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

zhangyangyu
  • 8,520
  • 2
  • 33
  • 43