Python脚本打开bash提示符终止脚本

时间:2010-11-15 23:29:51

标签: python bash process terminate chroot

我想在python中编写一个chroot包装器。该脚本将复制一些文件,设置其他一些东西,然后执行chroot,并将我放入chroot shell。

棘手的部分是我想要在chroot之后没有运行python进程。

换句话说,python应该进行设置工作,调用chroot并终止自身,让我进入chroot shell。当我退出chroot时,我应该在我调用python脚本时的目录中。

这可能吗?

2 个答案:

答案 0 :(得分:2)

我的第一个想法是使用os.exec*函数之一。这些将使用chroot进程(或您决定使用exec*运行的任何进程)替换Python进程。

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

(或类似的东西)

答案 1 :(得分: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
相关问题