pretty

Thursday, May 30, 2013

Concatenate files in python


cat folder/* > outfile

import fileinput
with open(outfilename, 'w') as fout:
for line in fileinput.input(filenames):
fout.write(line)

Thursday, April 25, 2013

Show specific line in large file

Show only line 20 

sed -n '20p' file_name

Show 10 through 20 

sed -n '10,20p' file_name

Show 10 and 20 

sed -n '10p;20p' file_name

Sunday, November 25, 2012

File modification time python



import os, time
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file)
print "last modified: %s" % time.ctime(mtime)

http://stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times-in-python

Wednesday, November 14, 2012

Update all python pip packages


import pip
from subprocess import call

for dist in pip.get_installed_distributions():
call("pip install --upgrade " + dist.project_name, shell=True)
i use it with ipython

sudo ipython
""" Cut the code above and type
%paste

Monday, November 5, 2012

Kill process with python on linux



import os
import signal

def kill_process(processname):
for line in os.popen("ps xa"):
fields = line.split()
pid = fields[0]
process = fields[4]
print process
if process == processname:
os.kill(int(pid), signal.SIGKILL)
break
else:
pass
look here for a windows solution or google it

Tuesday, October 30, 2012

Adding or subtracting a date in python

Some examples for calculating dates in the past and future.

import datetime
"""
use timedelta for rolling dates
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0,
hours=0, weeks=0)
"""
a_week_ago = datetime.datetime.now() - datetime.timedelta(weeks=1)
tomorrow = datetime.date.today() + datetime.timedelta(days=1)
print a_week_ago
#2012-10-23 21:58:00.109116
print tomorrow
#2012-10-31
#and so on . . .
more here
and here

Python datetime to unix timestamp

The most simple solution for converting datetime to unix timestamp


import datetime
import time
import calendar

#Returns string
d = datetime.datetime.now()
d.strftime('%s')

#another solution returns int
calendar.timegm(d.timetuple())

#Yet another solution, returns float
time.mktime(d.timetuple())