我試圖運行Python代碼進行測試和使用Emacs進行調試。我應該如何在* .py文件中調試和運行代碼?我嘗試使用M-x compile
命令。使用M-x compile
,我得到一個崩潰的編譯緩衝區(它表示Python正在編譯,但沒有任何反應)。你如何使用Emacs運行Python代碼?
回答
如果您正在使用emacs24這應該是默認的(在emacs23需要python.el,而不是Python-mode.el):
在Python緩衝區:
- 抄送鋯石:開放一個python殼
- CC CC:運行的緩衝區的內容,在打開殼蟒
- 抄送的Cr:運行所選擇的區域中的蟒殼
默認的Python殼「蟒蛇」,如果你東東使用IPython的,你可以在你的.emacs
(setq
python-shell-interpreter "ipython"
python-shell-interpreter-args "--colors=Linux --profile=default"
python-shell-prompt-regexp "In \\[[0-9]+\\]: "
python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
python-shell-completion-setup-code
"from IPython.core.completerlib import module_completion"
python-shell-completion-module-string-code
"';'.join(module_completion('''%s'''))\n"
python-shell-completion-string-code
"';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
只要您的IPython安裝在你的課程:)
IPython中的系統使用的conf > = 5具有自動完成功能,可以打破emacs子外殼,您可以通過更改此行來修復此問題 python-shell-interpreter-args "--colors=Linux --profile=default"
並添加--simple-prompt
。
它可以讓你正確地看到ipython,但由於某種原因,我還沒有得到在emacs的自動完成沒有像以前那樣有效。
如何使用Emacs運行Python代碼?
我正在運行Emacs 26,vanilla dev版本(自編自源碼克隆自Savannah)。
(請注意,在emacs的文檔,我們通常看到的,例如,按Ctrl - ç表示爲CC)
在Python模式(我通常使用CX比照「找到」進入(可能是新的)文件中的.py結尾),你就可以開始用Python的外殼,然後執行你的緩衝區的
if __name__ == '__main__':
有:
抄送CP(它執行運行Python創建與劣質的Python殼主要模式,殼牌編譯次要模式)
銅CC CC(與前綴參數執行蟒蛇殼發送緩衝區)
我們需要前綴參數傳遞給if __name__ == '__main__':
塊發送到下層的Python shell。
我們可以看到所有的按Ctrl的 - ç命令與按Ctrl - ç?
C-c C-c python-shell-send-buffer C-c C-d python-describe-at-point C-c C-f python-eldoc-at-point C-c C-j imenu C-c C-l python-shell-send-file C-c C-p run-python C-c C-r python-shell-send-region C-c C-s python-shell-send-string C-c C-t Prefix Command C-c C-v python-check C-c C-z python-shell-switch-to-shell C-c < python-indent-shift-left C-c > python-indent-shift-right C-c C-t c python-skeleton-class C-c C-t d python-skeleton-def C-c C-t f python-skeleton-for C-c C-t i python-skeleton-if C-c C-t m python-skeleton-import C-c C-t t python-skeleton-try C-c C-t w python-skeleton-while
檢查的蟒蛇殼發送緩衝區的幫助下(通過單擊它),我們可以看到:
python-shell-send-buffer is an interactive compiled Lisp function in ‘python.el’. (python-shell-send-buffer &optional SEND-MAIN MSG) Send the entire buffer to inferior Python process. When optional argument SEND-MAIN is non-nil, allow execution of code inside blocks delimited by "if __name__== '__main__':". When called interactively SEND-MAIN defaults to nil, unless it’s called with prefix argument. When optional argument MSG is non-nil, forces display of a user-friendly message if there’s no process running; defaults to t when called interactively.
按照docs銅是前綴參數 - 似乎是最通用的。
一種解決方法,可以讓我們避免使用前綴參數C-u的使用括號:
if (__name__ == '__main__'):
main()
而不是通常的:
if __name__ == '__main__':
main()
,然後C-C C-C本身執行的主要功能。