Skip to content

Instantly share code, notes, and snippets.

@franktoffel
Created May 31, 2017 23:09
Show Gist options
  • Save franktoffel/c6cd1324b6dbaff5dcf8652bf195b257 to your computer and use it in GitHub Desktop.
Save franktoffel/c6cd1324b6dbaff5dcf8652bf195b257 to your computer and use it in GitHub Desktop.
Python alternative to bash head command: prints the first -n lines of a text file defined within the string.
from IPython.core.magic import register_line_magic
from itertools import islice
@register_line_magic
def head(parameter_s=''):
'''Prints the first -n lines of a text file defined within the string.
Examples:
%head -n 5 file.txt
%head -5 file.txt
This file has to be placed in the startup subdirectory of your default IPython profile
e.g. 'user\.ipython\profile_default\startup'
'''
if not parameter_s:
raise Exception('Missing filename')
list_parameters = parameter_s.split()
assert len(list_parameters) <= 3, "Inappropriate command: use '%head -n 5 file.txt' or '%head -5 file.txt'"
filename = list_parameters[-1]
if len(list_parameters)==1:
N = 5
elif len(list_parameters)==2 and list_parameters[0][0] == "-":
try:
N = abs(int(list_parameters[0]))
except UsageError:
print("Inappropriate command: use '%head -n 5 file.txt' or '%head -5 file.txt'")
return
elif len(list_parameters)==3 and list_parameters[0] == "-n":
try:
N = abs(int(list_parameters[1]))
except UsageError:
print("Inappropriate command: use '%head -n 5 file.txt' or '%head -5 file.txt'")
return
else:
raise Exception("Inappropriate command: use '%head -n 5 file.txt' or '%head -5 file.txt'")
try :
with open(filename) as file:
for line in islice(file, N):
print(line)
except (ValueError, IOError):
print(filename+"?")
print("Error: no such file, variable, URL, history range or macro")
return
# In an interactive session, we need to delete these to avoid
# name conflicts for automagic to work on line magics.
del head
@jtara1
Copy link

jtara1 commented Sep 13, 2021

Add
#!/usr/local/bin python3
the the top of the file.
I'm also getting an error,
zsh: permission denied: magic_head

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment