Is there is way to show the current directory in IPython prompt?
Instead of this:
In [1]:
Something like this:
In<~/user/src/proj1>[1]:
Is there is way to show the current directory in IPython prompt?
Instead of this:
In [1]:
Something like this:
In<~/user/src/proj1>[1]:
You can use os.getcwd
(current working directory) or in the native os command pwd
.
In [8]: import os
In [9]: os.getcwd()
Out[9]: '/home/rockwool'
In [10]: pwd
Out[10]: '/home/rockwool'
Using ! before pwd will show the current directory
In[1]: !pwd
/User/home/
When interactive computing it is common to need to access the underlying shell. This is doable through the use of the exclamation mark ! (or bang) To execute a command when present in beginning of line.
According to:
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.
So, in .ipython/profile_default/ipython_config.py
, put something like:
c.PromptManager.in_template = "In<{cwd} >>>"
Assuming you're interested in configuring this for all subsequent invocations of ipython, run the following (in a traditional shell, like bash :) ). It appends to your default ipython configuration, creating it if necessary. The last line of the configuration file will also automatically make all the executables in your $PATH available to simply run in python, which you probably also want if you're asking about cwd in the prompt. So you can run them without a ! prefix. Tested with 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 only works in older versions of ipython.)
!dir
shows the current directory and the contained files. The directory is shown with single backslashes, that simplifies the handling of the path (at least when using windows).