【问题标题】:how to show current directory in ipython prompt如何在 ipython 提示符中显示当前目录
【发布时间】:2016-11-23 16:54:48
【问题描述】:

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

Instead of this:
In [1]:

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

【问题讨论】:

  • 显示当前工作目录可以使用 pwd 命令

标签: python ipython prompt


【解决方案1】:

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

In [8]: import os

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

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

【讨论】:

  • 这些命令我都知道,但是能不能在提示中显示出来,不用每次都输入?
【解决方案2】:

根据:

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

在终端中,可以自定义输入输出提示的格式。这目前不会影响其他前端。

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

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

【讨论】:

  • 是否可以只显示最后一个目录?我可以在 cwd 上写一个自定义函数吗,比如 split?
【解决方案3】:

使用! pwd 之前会显示当前目录

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

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

【讨论】:

  • pwd 未被识别为内部或外部命令
【解决方案4】:

假设您有兴趣为 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。)

【讨论】:

    【解决方案5】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-13
      • 1970-01-01
      • 2011-08-06
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多