2011-07-21 39 views
1

我正在編寫一個python腳本,它將在EC2機器上運行,如user-data-script。我試圖找出如何升級類似bash命令的機器上的軟件包:使用apt模塊更新python本身

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

我知道我可以使用apt包在python做到這一點:

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

問題是如果python本身是升級包之一,會發生什麼情況。有沒有辦法在這次升級後重新加載解釋器和腳本,並繼續停止它的位置?

現在,我唯一的選擇是使用shell腳本作爲我的用戶數據腳本,目的是升級包(可能包括python),然後將其放入python中作爲我的其餘代碼。我想消除使用shell腳本的額外步驟。

回答

0

我想我想通了:

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

使用鏈接。

#!/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之間切換,則可以根據需要將盡可能多的這些調用鏈接在一起。

+0

這可行,但我試圖減少我必須發送和/或寫出的腳本的數量,理想情況下只有一個Python腳本。 – vsekhar