Invalid Syntax when I use python-shell-send-buffer in Emacs Python-mode

Recently, I’m trying to configure emacs as my python IDE and I use anaconda in my computor. I have use conda package and python-mode in emacs in the init.el as following:

(use-package conda
  :ensure t
  :init
(setq conda-anaconda-home (expand-file-name "D:/Anaconda"))
(setq conda-env-home-directory (expand-file-name "D:/Anaconda/envs")))
(use-package python-mode
  :ensure t
  :hook (python-mode . lsp-deferred)
  :custom
  (dap-python-debugger 'debugpy)
  :config
  (require 'dap-python))

and in my anaconda env, I have five environments:

# conda environments:
#
base                  *  D:Anaconda
PyCharm                  D:AnacondaenvsPyCharm
Pyflow                   D:AnacondaenvsPyflow
gluon                    D:Anacondaenvsgluon
tensorflow               D:Anacondaenvstensorflow

I can open a shell in emacs and activate the base environment and run python. But in the emacs when I am trying to run a py file. When I use M-x run-python and it didn’t run my python scripts. After that, I try to use python-shell-send-buffer to run the script but it threw out the following eroor:

>>> Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:/Users/Travis/AppData/Local/Temp/pyQTizRq", line 1
    Python 3.8.5 (default, Sep  3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
           ^
SyntaxError: invalid syntax

And When I open this directory ”’c:/Users/Travis/AppData/Local/Temp/”’this file doesn’t exist. My system is windows 10 and emacs 27.2. How can I fix the problem and it can run the script directly?

Answer

The proper way to use python-shell-send-buffer is to run it from a buffer of Python code; Emacs will then send the contents of that buffer to the Python REPL you started with run-python.

Don’t run this command in the run-python buffer (*Python*) itself; it doesn’t make any sense to submit that buffer’s contents to Python as code.

To quickly demonstrate how this works,

  • Create a buffer demo.py and type some Python code into it.

    print("Hello Emacs")
    
  • Split the frame into two panes (oddly called “windows” in Emacs terminology) C-x 2

  • In one of the panes, execute M-x run-python

  • Switch to the other pane (C-x o), and execute M-x python-shell-send-buffer

  • Observe how the command gets entered at the Python REPL prompt in the *Python* buffer, and the results are visible there.

If the buffer with your Python code is running python-mode, there is a shortcut key C-c C-c to submit the buffer to the REPL, so you don’t need to type the long and complex M-x command sequence.

The evaluation function works by creating a temporary file in the background, but that will be gone again by the time you try to inspect it.