Skip to content

Instantly share code, notes, and snippets.

@kuba--
Created May 19, 2013 07:23
Show Gist options
  • Save kuba--/5606966 to your computer and use it in GitHub Desktop.
Save kuba--/5606966 to your computer and use it in GitHub Desktop.
unix wc | tail commands in python
def wc (fname, options = "-l"):
p = subprocess.Popen(['wc', options, fname], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result, err = p.communicate()
if p.returncode != 0:
return -1
return int(result.strip().split()[0])
def tail (fname, n = 30, out = subprocess.PIPE):
p = subprocess.Popen(['tail', '-n', str(n), fname], stdout=out, stderr=subprocess.PIPE)
result, err = p.communicate()
if p.returncode != 0:
return -1
return n
wc = wc("test.txt")
n = wc - 10
if n > 0:
with open("test-tail.txt", "w") as f:
tail("test.txt", n, f)
print "\ttail -n %d %s > %s" % (n, "test.txt", f.name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment