簡體   English   中英

在 Emacs 中設置 Python 項目根目錄?

[英]Set Python project root in Emacs?

emacs-for-python (基於python.el )提供了很好的功能來啟動 Python 進程並直接從 Emacs 發送緩沖區(通常你用Cc Cc來做)。 但是,這種方式會為每個緩沖區創建新進程,並將 Python 的工作目錄設置為相應文件的目錄。

相反,我希望將工作目錄設置為項目根目錄的單個 Python 進程。 或者甚至可能是幾個進程,但從根目錄開始,而不是模塊的目錄。


為什么我需要它? 都是關於進口的。 想象一下以下項目結構:

myproject
   package1
      __init__.py
      mod1.py
   package2
      __init__.py
      mod2.py

如果我在文件mod1.py上啟動 Python 進程,Emacs 會自動將工作目錄設置為myproject/package1 ,這樣我就只能從同一個包中導入模塊。 沒有從其他包導入。 沒有絕對進口。 疼痛。

目前我使用sys.path的技巧,例如:

import sys, os
sys.path.insert(0, os.path.join(os.path.abspath(__file__), '..', '..'))

在每個模塊的開頭。 但這真的,真的,真的很丑陋和不方便。

那么有沒有人有任何提示或技巧來為 Emacs 中的劣質進程設置 Python 的項目根目錄?

我不熟悉 emacs-for-python,但找到項目根目錄的路徑很簡單。

Projectile 提供了一個函數projectile-project-root 你可以在你的 mod1.py 緩沖區中調用它,它會返回"/path/to/myproject" 這假設 projectile 可以識別您的項目根目錄,如果您使用某種 VCS 就可以了。

好的,這應該讓你開始

(defvar my-python-shell-dir-setup-code 
  "import os
home = os.path.expanduser('~')
while os.path.isfile('__init__.py') and (os.getcwd() != home):
    os.chdir('..')
del os")

(defun my-python-shell-dir-setup ()
  (let ((process (get-buffer-process (current-buffer))))
    (python-shell-send-string my-python-shell-dir-setup-code process)
    (message "Setup project path")))

(add-hook 'inferior-python-mode-hook 'my-python-shell-dir-setup)

這是我們正在做的事情my-python-shell-dir-setup-code是簡單的 python 代碼,用於查找project-dir並設置它(它又快又臟,您可能想根據需要對其進行修改)。 然后我們添加一個inferior-python-mode-hook (即my-shell-dir-setup )來在創建shell 時在outerial shell 中執行python 代碼。

上面接受的答案是正確的,只是上面接受的答案中有一個錯誤。 提出的問題的正確解決方案是:

(defvar my-python-shell-dir-setup-code 
"import os
home = os.path.expanduser('~')
while (not os.path.isfile('__init__.py')) and (os.getcwd() != home):
    os.chdir('..')
del os")

(defun my-python-shell-dir-setup ()
  (let ((process (get-buffer-process (current-buffer))))
    (python-shell-send-string my-python-shell-dir-setup-code process)
    (message "Setup project path")))

(add-hook 'inferior-python-mode-hook 'my-python-shell-dir-setup)

不同之處在於while os.path.isfile('__init__.py') and (os.getcwd() != home):應該是while (not os.path.isfile('__init__.py')) and (os.getcwd() != home):

如果沒有__init__.py文件,我們想后退一個目錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM