Python脚本打开bash提示符终止脚本
问题描述:
我想在python中编写一个chroot包装器。该脚本将复制一些文件,设置一些其他的东西,然后执行chroot,并将我置于chroot shell中。Python脚本打开bash提示符终止脚本
棘手的部分是我在chroot后不想运行python进程。
换句话说,python应该做安装工作,调用chroot并终止自己,让我进入chroot shell。当我退出chroot时,我应该在我调用python脚本时的目录中。
这可能吗?
答
我的第一个想法是使用os.exec*
函数之一。这些将用chroot
进程替代Python进程(或任何您决定使用exec*
运行的进程)。
# ... do setup work
os.execl('/bin/chroot', '/bin/chroot', directory_name, shell_path)
(或类似的东西)
答
或者,你可以使用一个新的线程为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
由于当前目录是进程内部属性,所以返回到原始目录会自行处理。 – alexis 2012-02-18 22:38:25