mot*_*m79 8 python prompt ipython
有没有办法在IPython提示符下显示当前目录?
Instead of this:
In [1]:
Something like this:
In<~/user/src/proj1>[1]:
Run Code Online (Sandbox Code Playgroud)
Dur*_*tta 21
您可以使用os.getcwd(当前工作目录)或在本机os命令中使用pwd.
In [8]: import os
In [9]: os.getcwd()
Out[9]: '/home/rockwool'
In [10]: pwd
Out[10]: '/home/rockwool'
Run Code Online (Sandbox Code Playgroud)
根据:
https://ipython.org/ipython-doc/3/config/details.html#special-config-details
在终端中,可以自定义输入和输出提示的格式。目前这不会影响其他前端。
因此,在 中.ipython/profile_default/ipython_config.py,输入如下内容:
c.PromptManager.in_template = "In<{cwd} >>>"
Run Code Online (Sandbox Code Playgroud)
小智 6
使用 !在 pwd 将显示当前目录之前
In[1]: !pwd
/User/home/
Run Code Online (Sandbox Code Playgroud)
在交互式计算时,通常需要访问底层 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
Run Code Online (Sandbox Code Playgroud)
(c.PromptManager 仅适用于旧版本的 ipython。)