My First Newbie Python Program
Just started my Python class few days ago and it’s pretty cooler compared to PHP, I just got to notice that Python doesn’t like long codes it wants everything short and simple still compared to PHP. Stuffs like:
PHP:
<?php
for( $i = 1; $i <= 10; $i++ ) {
$r[] = $i;
}
echo implode( '<br />', $r );
Is shorter and simple in Python:
#!/usr/bin/python3 r = [] for i in range( 1, 10 ): r.extend( str( i ) ) print( '<br />'.join( r ) )
Am not a pro yet, am just that newbie 😀 So, I spent my time today to write a simple log preparer. This prepares any log file to html where you can view it in browser, mainly I did it for Apache access logs but I see it can work in other logs. Test and give me feedback 🙂 My codes might be childish but I pray to learn more soon 🙂
Source Code:
#!/usr/bin/python3
import sys, os
def prepare_log( log_dir = None, log_file = None, out = None ):
if log_dir is None:
log_dir = '/var/log/apache2/'
if log_file is None:
log_file = 'access.log'
if out is None:
out = 'access.log.html'
File = os.path.join( log_dir, log_file )
try:
print( 'Opening file...' )
with open( File, 'r' ) as log:
print( 'Reading file...' )
log_data_rows = log.read().split( '\n' )
with open( out, 'w' ) as out_file:
print( 'Writing file to ' + out )
out_file.write( prepareHTML( log_data_rows ) )
print( 'Done' )
except FileNotFoundError as e:
print( 'Unable to open file "' + File + '" \r\nReason: ' + e.strerror )
sys.exit()
def prepareHTML( rows ):
html = """
<html>
<head>
<title>Apache Access Logs</title>
<meta content=\"text/html;charset=utf-8\" name=\"Content-Type\">
<style>
table tr td {
padding : 7px;
border-bottom: 2px dotted #e7e7e7;
}
table tr.correct, .correct {
color : #00ac77;
}
table tr.failed, .failed {
color : #ef1616;
}
table tr:nth-child(odd) {
background : #e7e7e7;
}
</style>
<body>
<table>"""
row = []
i = 1
for line in rows:
if( line ):
data = '<tr><td> ' + str( i ) + '. </td> <td>' + line + '</td></tr>'
row.extend( data )
i += 1
html += ''.join( row ) + """
</table>
</body>
</html>"""
return html
try:
dir_path = str( input( 'Log directry path: ' ) )
file_name = str( input( 'Log file name' ) )
output = str( input( 'Output file (Default is access.log.html): ' ) )
except ValueError:
print( 'Only strings needed' )
if not dir_path:
dir_path = None
if not file_name:
file_name = None
if not output:
output = None
prepare_log( dir_path, file_name, output )
Save and run. Cheers!
Waiting feed back 🙂