简体   繁体   中英

Update python itself using the apt module

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.

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()

Use chaining.

#!/bin/sh
cat >next.sh <<'THEEND'
#!/bin/sh
#this normally does nothing
THEEND
chmod +x next.sh

python dosomestuff.py

exec next.sh

Inside the Python app, you would write out a shell script to do what you need. In this case, that shell script would upgrade Python. Since it runs after Python has shut down, there is no conflict. In fact, next.sh could start up the same (or another) Python app. If you alternate between two shell scripts first.sh and next.sh you could chain as many of these invocations together as you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM