簡體   English   中英

使用 apt 模塊更新 python 本身

[英]Update python itself using the apt module

我正在編寫一個 python 腳本,它將作為user-data-script在 EC2 機器上運行。 我試圖弄清楚如何升級機器上的軟件包,類似於 bash 命令:

$ sudo apt-get -qqy update && sudo apt-get -qqy upgrade

我知道我可以在 python 中使用apt package 來執行此操作:

import apt
cache=apt.Cache()
cache.update()
cache.open(None)
cache.upgrade()
cache.commit()

問題是如果 python 本身是升級的軟件包之一會發生什么。 有沒有辦法在此升級后重新加載解釋器和腳本並從中斷的地方繼續?

現在我唯一的選擇是使用 shell 腳本作為我的用戶數據腳本,其唯一目的是升級包(可能包括 python),然后放入 python 以獲取我的代碼的 rest。 我想消除使用 shell 腳本的額外步驟。

我想我想通了:

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

使用鏈接。

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

python dosomestuff.py

exec next.sh

在 Python 應用程序中,您將編寫一個 shell 腳本來執行您需要的操作。 在這種情況下,shell 腳本將升級 Python。 由於它是在 Python 關閉之后運行的,所以沒有沖突。 事實上, next.sh可以啟動同一個(或另一個)Python 應用程序。 如果您在兩個 shell 腳本first.shnext.sh之間交替使用,您可以將任意數量的這些調用鏈接在一起。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM