[Tutor] help with subprocess module

Mats Wichmann mats at wichmann.us
Sat Aug 19 14:30:37 EDT 2017


On 08/19/2017 04:13 AM, kay Cee wrote:
> I made a python script that will update a Ubuntu Server every second and
> writes asuccess message  and date to a log file, but for some reason the
> file is not being written to.
> 
> Here is the Script:
> 
> #!/usr/bin/python3
> 
> import subprocess
> import time
> import datetime
> 
> class UpdateError(Exception):
>     pass
> 
> def update():
>     while True:
>         try:
>             update_log = open('update_log.txt', 'r+')
>             time.sleep(1)
>             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'])
>         except UpdateError:
>             print("Update Error!!!")
>     update_log.close()
> 
> if __name__ == '__main__':
>     update()

Hate to not just "answer the question", but what are you trying to
accomplish with this script?

You certainly don't want to call "apt-get update -y" in loop this fast.
Why are you then rebooting? (update doesn't change the system, only the
apt cache info)

Ubuntu has a way to do this stuff as a background task anyway.

For logging, you may want to actually use Python logging facilities.


All those said, the way you want to debug something like this is to run
a much more benign task through subprocess, before moving on to big (and
slow) tasks.



More information about the Tutor mailing list