[Python] Python in emacs: __name__ == '__main__', but somehow not

Discussão em 'Python' iniciado por Stack, Maio 23, 2025.

  1. Stack

    Stack Membro Participativo

    I am coding python in emacs. However, somehow the python interpreter running in emacs manages to surprise me.

    If I write

    print()
    print(__name__)
    print(__name__=='__main__')
    if __name__ == '__main__':
    print("indeed")


    in an emacs buffer, and tell emacs to start an interpreter and run the content of this buffer, I get a buffer containing

    Python 3.3.5 (default, Mar 18 2014, 02:00:02)
    [GCC 4.2.1 20070831 patched [FreeBSD]] on freebsd9
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    __main__
    True
    >>>


    (Both __main__ and True are the outputs from the print statement; the python buffer always displays the >>> and prints immediately after it. I am aware of this, this is not a problem.)

    From the command line, both python and python -i show the 'indeed', as expected.

    How is Emacs able to the inconsistency of evaluating __name__=='__main__' to True, while not executing things inside if __name__ == '__main__':? And how do reconfigure it so it does not do so any more?

    Continue reading...

Compartilhe esta Página