one thing that i do to trim code down a little is leave out the == or != when i know I will be dealing with small integers, like:
if proc.poll():
# non-zero return from process equates to true
print("failure")
else:
# zero return from process equates to false
print("success")
i've also been using the 'with' statement when dealing with files, maybe not as important on such a small script, but i like it anyway.
try:
with open('/var/www/ServerOverview.txt', 'a') as Log:
Log.write('some stuff')
# file is closed at the end of 'with'
except IOError as exOS:
# unable to open file, disk is full, file not found, etc.
print("Unable to open file.")
chriswelborn
Junior Poster in Training
73 posts since Jul 2009
Reputation Points: 43
Solved Threads: 4
Skill Endorsements: 1
I would try to learn to use functions for clarity, import subprocess is superfluous and unused as only separaterly imported Popen is used. Try..except suggestion for opening suggested by chriswelborn is also good one.
Untested code to give the idea (those functions look nice to have, so let's also enable the import as module):
import os
from subprocess import Popen
# Error not warning as we raise exception from main
class PriviledgeError(Exception):
pass
try:
if os.getuid():
raise PriviledgeError("Priviledge Error : YOU MUST RUN THIS APPLICATION AS SU")
except AttributeError:
# Windows has not os.getuid()
print 'Could not check priviledges, no getuid command'
def log_it(lf, task, message, words = ('COMPLETE', 'FAILED')):
lf.write('\n\n' + message)
lf.write(' ' + words[bool(task.poll())])
def do_and_wait(command, lf, message):
task = Popen(command)
task.wait()
log_it(lf, task, message)
def banner(text, n=60, char='-'):
return '''
{line}
{message}
{line}
'''.format(line=n*char, message=text.upper().center(n))
if __name__ == '__main__':
print(banner('PROCESS STARTING - VIRUS DEFINITION UPDATE AND SCAN'))
with open('/var/www/ServerOverview.txt', 'a') as log:
do_and_wait(['freshclam'], log, 'VIRUS UPDATE')
do_and_wait(['clamscan', '-r', '/'], log, 'VIRUS SCAN')
pyTony
pyMod
6,312 posts since Apr 2010
Reputation Points: 879
Solved Threads: 987
Skill Endorsements: 26
Question Answered as of 3 Months Ago by
chriswelborn
and
pyTony