import requests
import os
import sys
import re
import subprocess
from jinja2 import Environment, meta, Template
import shutil
from getpass import getpass
from random import randint
from distutils import spawn

#import time


def execute(command):
    process = subprocess.Popen(
        command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    # Poll process for new output until finished
    while True:
        nextline = process.stdout.readline()
        if nextline == '' and process.poll() is not None:
            break
        sys.stdout.write(nextline)
        sys.stdout.flush()

    output = process.communicate()[0]
    exitCode = process.returncode

    if not exitCode:
        return output
    else:
        raise Exception(command, exitCode, output)


def download_file(url, path):
    if os.path.isfile(path):
        print("already downloaded iso. continuing.")
        return path
    filename = os.path.basename(path)
    print("downloading to " + filename)
    # NOTE the stream=True parameter
    r = requests.get(url, stream=True)