如何在 ipython 提示符中显示当前目录

how to show current directory in ipython prompt

有没有办法在IPython提示符中显示当前目录?

Instead of this:
In [1]:

Something like this:
In<~/user/src/proj1>[1]:

您可以使用 os.getcwd(当前工作目录)或在本机 os 命令中 pwd

In [8]: import os

In [9]: os.getcwd()
Out[9]: '/home/rockwool'

In [10]: pwd
Out[10]: '/home/rockwool'

根据:

https://ipython.org/ipython-doc/3/config/details.html#specific-config-details

In the terminal, the format of the input and output prompts can be customised. This does not currently affect other frontends.

因此,在 .ipython/profile_default/ipython_config.py 中,输入如下内容:

c.PromptManager.in_template = "In<{cwd} >>>"

正在使用!在 pwd 之前将显示当前目录

In[1]: !pwd
/User/home/

交互式计算时,通常需要访问底层 shell。这可以通过使用感叹号来实现! (或 bang)在行首出现时执行命令。

假设您有兴趣为以下 ipython、运行 的所有后续调用配置它(在传统的 shell 中,例如 bash :)) .它附加到您的默认 ipython 配置,必要时创建它。配置文件的最后一行还将自动使 $PATH 中的所有可执行文件仅供 python 中的 运行 使用,如果您在提示中询问 cwd,您可能也需要这样做。所以你可以 运行 他们没有!字首。使用 IPython 7.18.1.

测试
mkdir -p ~/.ipython/profile_default
cat >> ~/.ipython/profile_default/ipython_config.py <<EOF

from IPython.terminal.prompts import Prompts, Token
import os

class MyPrompt(Prompts):
    def cwd(self):
        cwd = os.getcwd()
        if cwd.startswith(os.environ['HOME']):
            cwd = cwd.replace(os.environ['HOME'], '~')
            cwd_list = cwd.split('/')
            for i,v in enumerate(cwd_list):
                if i not in (1,len(cwd_list)-1): #not last and first after ~
                    cwd_list[i] = cwd_list[i][0] #abbreviate
            cwd = '/'.join(cwd_list)
        return cwd

    def in_prompt_tokens(self, cli=None):
        return [
                (Token.Prompt, 'In ['),
                (Token.PromptNum, str(self.shell.execution_count)),
                (Token.Prompt, '] '),
                (Token, self.cwd()),
                (Token.Prompt, ': ')]

c.TerminalInteractiveShell.prompts_class = MyPrompt
c.InteractiveShellApp.exec_lines = ['%rehashx']
EOF

(c.PromptManager 仅适用于旧版本的 ipython。)

!dir 显示当前目录和包含的文件。该目录以单个反斜杠显示,这简化了路径的处理(至少在使用 windows 时)。