[Tutor] Logical error?
Bob Williams
linux at barrowhillfarm.org.uk
Sat May 3 00:19:26 CEST 2014
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Hi,
I'm fairly new to coding and python. My system is linux (openSUSE
13.1). I've written the following code to examine a log file, and
extract strings from certain lines if two conditions are met, namely
that the file has been modified today, and the line contains the
string 'recv'.
- ---Code---
#!/usr/bin/python
import sys
import datetime
import codecs
import subprocess
# Format date as YYYY/MM/DD
today = (datetime.datetime.now()).strftime('%Y/%m/%d')
fullPath = [] # declare (initially empty) lists
truncPath = []
with codecs.open('/var/log/rsyncd.log', 'r') as rsyncd_log:
for line in rsyncd_log.readlines():
fullPath += [line.decode('utf-8', 'ignore').strip()]
if fullPath[-1][0:10] == today:
print("\n Rsyncd.log has been modified in the last 24 hours...")
else:
print("\n No recent rsync activity. Nothing to do.\n")
sys.exit()
# Search for lines starting with today's date and containing 'recv'
# Strip everything up to and including 'recv' and following last '/'
path separator
for i in range(0, len(fullPath)):
if fullPath[i][0:10] == today and 'recv' in fullPath[i]:
print("got there")
begin = fullPath[i].find('recv ')
end = fullPath[i].rfind('/')
fullPath[i] = fullPath[i][begin+5:end]
truncPath.append(fullPath[i])
print(" ...and the following new albums have been added:\n")
else:
print(" ...but no new music has been downloaded.\n")
sys.exit()
- ---Code---
The file rsyncd.log typically contains lines such as (sorry about the
wrapping):
2014/05/02 19:43:14 [20282]
host109-145-nnn-xxx.range109-145.btcentralplus.com recv Logical
Progression Level 3 (1998) Intense/17 Words 2 B Heard Collective -
Sonic Weapon.flac 72912051 72946196
I would expect the script to output a list of artist and album names,
eg Logical Progression Level 3 (1998) Intense. IOW what is between the
string 'recv' and the trailing '/'. What it actually produces is:
:~> python ~/bin/newstuff.py
Rsyncd.log has been modified in the last 24 hours...
...but no new music has been downloaded.
This suggests that the first 'if' clause (matching the first 10
characters of the last line) is satisfied, but the second one isn't,
as the flow jumps to the second 'else' clause.
As the script runs without complaint, this is presumably a logical
error rather than a syntax error, but I cannot see where I've gone wrong.
Bob
- --
Bob Williams
System: Linux 3.11.10-7-desktop
Distro: openSUSE 13.1 (x86_64) with KDE Development Platform: 4.13.0
Uptime: 06:00am up 11:26, 4 users, load average: 0.00, 0.02, 0.05
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/
iEYEARECAAYFAlNkGewACgkQ0Sr7eZJrmU57YwCgg91pxyQbFMSe+TqHkEjMuzQ6
03MAnRQ50up6v+kYE+Hf/jK6yOqQw4Ma
=+w0s
-----END PGP SIGNATURE-----
More information about the Tutor
mailing list