【问题标题】:Python Writing a 512-byte block of zeros to /dev/sda works, but doesn't behave like it is workingPython 将一个 512 字节的零块写入 /dev/sda 可以工作,但不能正常工作
【发布时间】:2015-05-19 02:04:04
【问题描述】:

在这里,我正在尝试创建一个函数来(最终)支持使用多种规范擦除驱动器。我遇到的问题是,当我尝试将 ZeroBlock 写入磁盘时,它会被写入,但是代码的行为就像它失败了一样。我说它有效的原因是它从我的测试系统中的驱动器中清除了引导扇区

def WipeDisk(Drive, WipeSpec, Passes):
    DiskSize = int(System.HDD[Drive].Size)
    DiskSect = int(System.HDD[Drive].Sectors())
    SectSize = int(System.HDD[Drive].SectSz)
    System.HDD[Drive].Start = time.time()
    if (WipeSpec == "Zero"):
            with open("/dev/zero", "rb") as Zero:
                    ZeroBlock = Zero.read(SectSize)
            Zero.close()
            Pass = 0
            with open(System.HDD[Drive].Device, "wb") as Disk:
                    while (Pass < Passes):
                            Current = 1
                            while (Current < DiskSect):
                                    if (Disk.write(ZeroBlock)):
                                            if (Current %((DiskSect*Passes)/100) == 0):
                                                    (variable updates)
                                            if (Current == DiskSect):
                                                    Pass = (Pass+1)
                                    else:
                                            System.HDD[Drive].Error = 1
                                            Pass = Passes
                                            break
                                    Current = (Current+1)
                    if (Pass == Passes):
                            System.HDD[Drive].Current = Current
                            System.HDD[Drive].Percent = "100"
                            System.HDD[Drive].Complete = 1
                    Disk.close()
    else:
            print("Unknown Wipe Specification: "+WipeSpec)

【问题讨论】:

  • 你能更好地定义“表现得好像失败了”
  • if (Disk.write(ZeroBlock)): 之后的语句从不执行。它直接跳到相关的 else: 设置 System.HDD[Drive].Error = 1 的地方
  • 那里有一堆似乎没有必要的代码,而其他东西却不见了。也就是说,您的代码一开始就非常不符合 Python 风格,特别是您还没有理解 with 的想法。我什至会在尝试查找其中的任何错误之前清理所有这些内容,您很有可能会在途中发现并修复错误。

标签: python disk-io


【解决方案1】:

The documentation for file.write 说:

将字符串写入文件。没有返回值。

您似乎错误地假设write 返回某个值,指示写入是否成功。没有。

【讨论】:

  • 不确定每次我查看 .write() 手册时我是如何设法错过那一行的。既然如此,我将如何确定 write() 的成功或失败?对于数据破坏,我不能简单地希望它有效,我需要验证
  • @AntonTakk:如果出现某种 I/O 错误,它应该引发异常。但是,如果您出于安全目的想更加确定,您应该从磁盘读回值并验证它们是否为零。
猜你喜欢
  • 1970-01-01
  • 2017-02-06
  • 1970-01-01
  • 2011-08-29
  • 1970-01-01
  • 2021-01-05
  • 1970-01-01
  • 1970-01-01
  • 2020-03-25
相关资源
最近更新 更多