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

3
我想用Python编写一个chroot包装器。脚本将复制一些文件,设置其他一些东西,然后执行chroot,并应该让我进入chroot shell。
棘手的部分是,在我进入chroot之后,我不希望有任何Python进程在运行。
换句话说,Python应该完成设置工作,调用chroot并终止自身,让我进入chroot shell。当我退出chroot时,我应该在调用Python脚本时所在的目录中。
这可能吗?
2个回答

2

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

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

(or something like that)


返回原始目录是自动处理的,因为当前目录是进程内部属性。 - alexis

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接