for i in range(1, 11): print("循环次数", i) startsizeList = ["1M", "10G", "20G", "30G", "40G", "50G", "60G", "70G", "80G", "90G"] print("分区开始位置", startsizeList[i - 1]) endsize = str(10 * i) + "G" print("分区结束位置", endsize) # 分区 stdout, stderr = rc.diskOfParted(self.ip, self.user, self.passwd, self.addr_disk_dict[diskaddrlist2[j]], startsizeList[i - 1], endsize) print(stdout, stderr) if "nvme" in self.addr_disk_dict[diskaddrlist2[j]]: diskpart = self.addr_disk_dict[diskaddrlist2[j]] + "p" + str(i) print("分区名称:", diskpart) else: diskpart = self.addr_disk_dict[diskaddrlist2[j]] + str(i) print("分区名称:", diskpart) # 格式化 stdout, stderr = rc.diskOfMkfs(self.ip, self.user, self.passwd, diskpart) print(stdout, stderr) # 创建挂载目录 mountdirpath = "/home/" + stamplist[j] + "/mnt%s" % (i) print("挂载目录", mountdirpath) rc.createDir(self.ip, self.user, self.passwd, mountdirpath) # 挂载分区 stdout, stderr = rc.diskOfMount(self.ip, self.user, self.passwd, diskpart, mountdirpath) diffout = operator.contains(stderr, "") print("挂载分区操作返回结果校验无报错", diffout) 优化代码
时间: 2024-01-02 21:04:46 浏览: 119
可以考虑将一些重复的代码提取出来,例如:
1. 将分区开始位置和分区结束位置的列表提前定义,不需要每次都在循环内部定义。
2. 将打印分区名称的代码进行封装,避免重复。
3. 将创建挂载目录和挂载分区的代码进行封装,避免重复。
优化后的代码如下:
```
startsizeList = ["1M", "10G", "20G", "30G", "40G", "50G", "60G", "70G", "80G", "90G"]
for i in range(1, 11):
print("循环次数", i)
print("分区开始位置", startsizeList[i - 1])
endsize = str(10 * i) + "G"
print("分区结束位置", endsize)
# 分区
stdout, stderr = rc.diskOfParted(self.ip, self.user, self.passwd, self.addr_disk_dict[diskaddrlist2[j]], startsizeList[i - 1], endsize)
print(stdout, stderr)
# 打印分区名称
if "nvme" in self.addr_disk_dict[diskaddrlist2[j]]:
diskpart = self.addr_disk_dict[diskaddrlist2[j]] + "p" + str(i)
else:
diskpart = self.addr_disk_dict[diskaddrlist2[j]] + str(i)
print("分区名称:", diskpart)
# 格式化
stdout, stderr = rc.diskOfMkfs(self.ip, self.user, self.passwd, diskpart)
print(stdout, stderr)
# 创建挂载目录和挂载分区
mountdirpath = "/home/" + stamplist[j] + "/mnt%s" % (i)
rc.createDirAndMount(self.ip, self.user, self.passwd, diskpart, mountdirpath)
```
其中,`createDirAndMount` 是封装了创建挂载目录和挂载分区的函数。
阅读全文