[Tutor] help with subprocess module
Alan Gauld
alan.gauld at yahoo.co.uk
Sat Aug 19 15:29:22 EDT 2017
On 19/08/17 11:13, kay Cee wrote:
> import subprocess
> import time
> import datetime
>
> class UpdateError(Exception):
> pass
In defining your own type of Exception you implicitly
say that you will be raising it somewhere. But you
never raise this exception in your code...
> def update():
> while True:
> try:
> update_log = open('update_log.txt', 'r+')
> time.sleep(1)
Do you really want to run apt-get update every second?
That seems way too frequent, every hour would be a lot,
every day more reasonable.
> subprocess.call(['apt-get', 'update', '-y'])
> date = datetime.datetime.now()
> update_log.write("System was updated sucessfully on {}\n".format
> (str(date)))
> subprocess.call(['reboot'])
And do you want your computer rebooting after every
successful apt-get update? You really should not have
to do that. Especially every second, you are likely
to make your system unusable.
> except UpdateError:
> print("Update Error!!!")
Since nothing raises an UpdateError you will never receive one.
You are more likely to get an OSError or an IOError or a
FileNotFound or similar.
> update_log.close()
Since you open the file inside the loop you should close
it inside the loop. Ideally inside a finally clause.
Or better still use a with... construct to open the
file then you don;t need to close it yourself.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list