download_url = 'https://www.python.org/ftp/python/3.10.7/python-3.10.7-amd64.exe' ## provide your download url here
download_path = 'C:\\ProgramData\\Python' ## provide your path here where the file has to been downloaded
file_name = 'python.exe' ## provide your file name with extention
src_path = download_path+'\\'+file_name
import os 
import subprocess
import ctypes
import urllib2
import ssl
import getpass as gt


def download(fromURL,DownTo):
	print('File Downloading......')
	headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
	context = ssl._create_unverified_context()
	request = urllib2.Request(fromURL, headers=headers)
	req = urllib2.urlopen(request,context=context)
	try:
		with open(DownTo, 'wb') as f:
			while True:
				chunk = req.read(100*1000*1000)
				if chunk:
					f.write(chunk)
				else:
					break
		if os.path.isfile(DownTo):
			print("File Downloaded...")
			return "Success"
	except:
		return 'Please Check URL or Download Path!'
		
def install(path):
	print("Installing Python...")
	cmd = '"'+src_path+'"'+' /quiet'
	obj = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
	out, err = obj.communicate()
	if err:
		print(err)
	else:
		print('Python installed successfully...')
        return "Success"
 
def uninstall(cmd):
	command = '"'+cmd+'"'+' /uninstall /quiet'
	obj = subprocess.Popen(command, shell=True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
	out, err = obj.communicate()
	if err:
		print(err)
	else:
		print('Python uninstalled successfully...')
        return "Success"
 

def download_and_install():
	DOWNLOAD = download(download_url,src_path)
	if DOWNLOAD == "Success":
		INSTALL = install(src_path)
		if INSTALL == "Success":
			pass 
		else:
			print("Error occurred while installing Python...!")
	else:
		print("Error occurred while downloading the file...!")

if os.path.exists(download_path):
	pass 
else:
	os.makedirs(download_path)

uninstall_path = []
cache = []
user = gt.getuser()
cache_path = 'C:\\Users\\'+user+'\\AppData\\Local\\Package Cache'
if os.path.exists(cache_path):
	for file in os.listdir(cache_path):
		d = os.path.join(cache_path, file)
		cache.append(d)
	if len(cache) > 0:
		for i in cache:
			for file in os.listdir(i):
				if file.startswith("python") and file.endswith(".exe"):
					d = os.path.join(i, file)
					uninstall_path.append(d)
					break
		if len(uninstall_path) > 0:
			print("Already a version of Python is found in your device...")
			print("Uninstalling Previous version of Python...")
			UNINSTALL = uninstall(uninstall_path[0])
			if UNINSTALL == "Success":
				DOWNLOAD = download(download_url,src_path)
				if DOWNLOAD == "Success":
					INSTALL = install(src_path)
					if INSTALL == "Success":
						pass 
					else:
						print("Error occurred while installing Python...!")
				else:
					print("Error occurred while downloading the file...!")
			else:
				print("Error occurred while Uninstalling Previous version of Python...!")
		else:
			download_and_install()
	else:
		download_and_install()


else:
	download_and_install() 


