shell.py 文件源码

python
阅读 24 收藏 0 点赞 0 评论 0

项目:NeoAnalysis 作者: neoanalysis 项目源码 文件源码
def shell(cmd):
    """Run each line of a shell script; raise an exception if any line returns
    a nonzero value.
    """
    pin, pout = os.pipe()
    proc = sp.Popen('/bin/bash', stdin=sp.PIPE)
    for line in cmd.split('\n'):
        line = line.strip()
        if line.startswith('#'):
            print('\033[33m> ' + line + '\033[0m')
        else:
            print('\033[32m> ' + line + '\033[0m')
        if line.startswith('cd '):
            os.chdir(line[3:])
        proc.stdin.write((line + '\n').encode('utf-8'))
        proc.stdin.write(('echo $? 1>&%d\n' % pout).encode('utf-8'))
        ret = ""
        while not ret.endswith('\n'):
            ret += os.read(pin, 1)
        ret = int(ret.strip())
        if ret != 0:
            print("\033[31mLast command returned %d; bailing out.\033[0m" % ret)
            sys.exit(-1)
    proc.stdin.close()
    proc.wait()
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号