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

I am coding python in emacs. However, somehow the python interpreter running in emacs amazes me.

If i write

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

in emacs buffer and tell emacs to start the interpreter and run the contents 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 outputs from the print statement, the python buffer always displays >>> and prints right after it. I know that, this is not a problem.)

From the command line, both python and python -i show "really" as expected.

How is Emacs capable of inconsistencies in evaluating __name__=='__main__' to True , but doesn't do things inside if __name__ == '__main__': :? And how to reconfigure it so that it no longer does this?

+7
python emacs
source share
2 answers

Like @Wooble mentioned in the comment , this could be a python.el problem: Cc Cc works
python-shell-send-buffer :

python-shell-send-buffer is an interactive compiled Lisp function in `Python.el".

(python-shell-send-buffer & optional ARG)

Send the entire buffer to the lower Python process. With the ARG prefix, allow code execution inside blocks separated by the symbol "if __name__=='__main__':"

ie, to print "really," add the prefix Cu Cc Cc .

Q: I tried to break through python.el, and I still don't know how and where it does it. Can you explain, so that I can change the default behavior?

To find out what Cc Cc does in your case, run the python file and type Mx describe-key RET and then Cc Cc (actually press the keys). By default, it executes the python-shell-send-buffer function in python.el . You can override the keys for calling a function with an argument so that Cc Cc behaves like Cu Cc Cc , which allows you to run "if __name__=='__main__':" part:

 ;; Make Cc Cc behave like Cu Cc Cc in Python mode (require 'python) (define-key python-mode-map (kbd "Cc Cc") (lambda () (interactive) (python-shell-send-buffer t))) 
+4
source share

Once you have started the python shell, you can simply override the variable:

 __name__ = 'repl' 

This prevents the execution of any if __name__=='__main__': blocks on subsequent calls to Cc Cc .

0
source share

All Articles