2010-11-15 126 views
3

我想在python中編寫一個chroot包裝器。該腳本將複製一些文件,設置一些其他的東西,然後執行chroot,並將我置於chroot shell中。Python腳本打開bash提示符終止腳本

棘手的部分是我在chroot後不想運行python進程。

換句話說,python應該做安裝工作,調用chroot並終止自己,讓我進入chroot shell。當我退出chroot時,我應該在我調用python腳本時的目錄中。

這可能嗎?

回答

2

我的第一個想法是使用os.exec*函數之一。這些將用chroot進程替代Python進程(或任何您決定使用exec*運行的進程)。

# ... do setup work 
os.execl('/bin/chroot', '/bin/chroot', directory_name, shell_path) 

(或類似的東西)

+0

由於當前目錄是進程內部屬性,所以返回到原始目錄會自行處理。 – alexis 2012-02-18 22:38:25

0

或者,你可以使用一個新的線程爲POPEN命令,以避免阻塞主代碼,然後通過命令結果返回。

import popen2 
import time 
result = '!' 
running = False 

class pinger(threading.Thread): 
    def __init__(self,num,who): 
     self.num = num 
     self.who = who 
     threading.Thread.__init__(self) 

    def run(self): 
     global result 
     cmd = "ping -n %s %s"%(self.num,self.who) 
     fin,fout = popen2.popen4(cmd) 
     while running: 
      result = fin.readline() 
      if not result: 
       break 
     fin.close() 

if __name__ == "__main__": 
    running = True 
    ping = pinger(5,"127.0.0.1") 
    ping.start() 
    now = time.time() 
    end = now+300 
    old = result 
    while True: 
     if result != old: 
      print result.strip() 
      old = result 
     if time.time() > end: 
      print "Timeout" 
      running = False 
      break 
     if not result: 
      print "Finished" 
      break