1:环境:
- centos 7
- python2.7
2:脚本内容:
#!/usr/bin/env python import os import sys import requests import tarfile import shutil import subprocess # Install necessary packages try: subprocess.check_call(["yum", "install", "-y", "wget", "gcc", "make", "openssl-devel", "bzip2-devel", "zlib-devel", "libffi-devel"]) except subprocess.CalledProcessError: print("Failed to install necessary packages. Please check your system configuration and try again.") sys.exit(1) # Step 1: Check for root privileges if os.geteuid() != 0: print("This script must be run as root!") sys.exit(1) # Step 2: Check if the desired version is already installed current_version = sys.version_info if current_version >= (3, 10): print("You already have the latest version of Python ({0}.{1}).".format(current_version.major, current_version.minor)) sys.exit(0) # Step 3: Prompt user for desired version and download it desired_version = raw_input("Please enter the version of Python you want to install (e.g., '3.9.7'): ") download_url = "https://mirrors.huaweicloud.com/python/" + str(desired_version) + "/Python-" + str(desired_version) + ".tgz" download_file = "Python-" + str(desired_version) + ".tgz" try: response = requests.get(download_url) with open(download_file, "wb") as f: f.write(response.content) except requests.exceptions.RequestException: print("Failed to download Python. Please check your network connection and try again.") sys.exit(1) # Step 4: Check if the download was successful if not os.path.exists(download_file): print("Failed to download " + download_file + ". Please check your network connection and try again.") sys.exit(1) # Step 5: Extract the downloaded file try: with tarfile.open(download_file) as tar: tar.extractall() except (OSError, tarfile.TarError): print("Failed to extract Python. Please check your download file and try again.") sys.exit(1) # Step 6: Compile and install Python try: subprocess.check_call(["./configure", "--prefix=/usr/local/python3.10"], cwd="Python-" + desired_version) subprocess.check_call(["make"], cwd="Python-" + desired_version) subprocess.check_call(["make", "install"], cwd="Python-" + desired_version) except subprocess.CalledProcessError: print("Failed to compile or install Python. Please check your installation dependencies and try again.") sys.exit(1) # Step 7: Modify the python path in the yum command backup_file = "/usr/bin/yum.bak" if not os.path.exists(backup_file): os.rename("/usr/bin/yum", backup_file) with open(backup_file, "r") as f: content = f.read() if "#!/usr/bin/python" in content: content = content.replace("#!/usr/bin/python", "#!/usr/bin/python2") with open("/usr/bin/yum", "w") as f: f.write(content) # Step 8: Print a success message print("Python " + desired_version + " has been installed successfully and set as the default version!")
标签:自定义,desired,python,一键,try,Python,version,file,download From: https://www.cnblogs.com/xlei/p/17326622.html