Nov 10, 2024
Posted by:
If you are a developer on Linux or Mac you will most likely be using the head and tail commands quite often. They are really very handy tools. Ever wished that you could use these commands when using WIndows?
Here's how I implemented a head and tail command for iPython and Jupyter on Windows. On Powershell you can use a command which has the same functionality as the Linux tail or head command but the syntax is more verbose.
Get-Content filename -Head n
Get-Content filename -Tail n
As an example let's look at a simple Python script like this :
square.py | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # square.py import turtle # Allows us to use the turtle module wn = turtle.Screen() # Create a window for turtles mike = turtle.Turtle() # Create a turtle, assign to mike mike.forward(50) # Draw a square mike.left(90) mike.forward(50) mike.left(90) mike.forward(50) mike.left(90) mike.forward(50) mike.left(90) wn.mainloop() # Wait for events, such as closing window |
On Linux/Mac terminal if you wanted to view the first 5 lines of this file, you just issue this command
head -5 square.py
On Powershell you can do the following :
Get-Content square.py -Head 5
You can see that it's more verbose.
If you are on the Windows command prompt (DOS) you can enter the command like this :
powershell -command "& Get-Content square.py -Head 5"
Much too verbose for my liking and I am not inclined to use it as such.
However we can create aliases in IPython or Jupyter for these commands to make it more usable :
% alias head powershell -command "& {Get-Content %s -Head %s}"
With that defined in IPython shell, we can then call
%head square.py 5 # first 5 lines
%head square.py 10 # first 10 lines
You can similarly create the alias for the tail command.
To persist the aliases across sessions, store them with the %store magic command :
%store head
%store tail
When you start a new iPython/Jupyter session you need to restore the stored variables with
% store -r
To automatically restore stored variables at startup, add this line to your ipython_config.py file :
c.StoreMagics.autorestore = True
If you do not have a config file yet, create one with the command
ipython create profile