Issue
I am writing a python script that will run on an EC2 machine as the user-data-script. I'm trying to figure out how I can upgrade the packages on the machine similar to the bash command:
$ sudo apt-get -qqy update && sudo apt-get -qqy upgrade
I know I can use the apt
package in python to do this:
import apt
cache=apt.Cache()
cache.update()
cache.open(None)
cache.upgrade()
cache.commit()
Problem is what happens if python itself was one of the packages that was upgraded. Is there a way to reload the interpreter and script following this upgrade and continue where it left off?
Right now my only choice is to use a shell script as my user-data script for the sole purpose of upgrading packages (including possibly python) and then dropping into python for the rest of my code. I'd like to eliminate the extra step of using a shell script.
Solution
I think I figured it out:
def main():
import argparse
parser = argparse.ArgumentParser(description='user-data-script.py: initial python instance startup script')
parser.add_argument('--skip-update', default=False, action='store_true', help='skip apt package updates')
# parser.add_argument whatever else you need
args = parser.parse_args()
if not args.skip_update:
# do update
import apt
cache = apt.Cache()
cache.update()
cache.open(None)
cache.upgrade()
cache.commit()
# restart, and skip update
import os, sys
command = sys.argv[0]
args = sys.argv
if skipupdate:
args += ['--skip-update']
os.execv(command, args)
else:
# run your usual code
pass
if __name__ == '__main__':
main()
Answered By - vsekhar Answer Checked By - Terry (WPSolving Volunteer)