要在Linux上格式化磁盘,可以使用Python的subprocess模块执行命令行命令。下面是一个示例代码,可以使用fdisk命令格式化磁盘:

import subprocess

def format_disk(disk_path):
    # 创建fdisk命令
    cmd = "echo -e 'n\np\n1\n\n\nw\n' | fdisk {}".format(disk_path)
    
    # 执行命令
    process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, error = process.communicate()
    
    if process.returncode != 0:
        print("格式化磁盘出错:")
        print(error.decode())
    else:
        print("磁盘格式化成功")

# 调用函数进行磁盘格式化
format_disk("/dev/sda")

请注意,这只是一个示例代码,仅适用于使用fdisk命令格式化磁盘的情况。具体的命令和参数可能因操作系统和需求而有所不同。请根据实际情况进行修改

Python原生代码格式化Linux上的磁盘

原文地址: https://www.cveoy.top/t/topic/ig4I 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录