sys.stdout.write()和sys.stdout.flush()的使用

最近写了一段代码, 根据一个list找到对应的文件, 写入到tfrecord中, 其中想要动态显示写入的进度, 于是去学习了一下发现sys.stdout可以解决这个问题

def create_tf_record(output_filename, image_dir, label_dir, examples):
  writer = tf.python_io.TFRecordWriter(output_filename)
  for idx, example in enumerate(examples):
    sys.stdout.write('\r>> Converting image %d/%d' % (idx + 1, len(examples)))
    sys.stdout.flush()
    if (idx+1) % 10000 == 0:
        break

    image_path = os.path.join(image_dir, example)
    label_path = os.path.join(label_dir, example)

    tf_example = dict_to_tf_example(image_path, label_path)
    writer.write(tf_example.SerializeToString())

  sys.stdout.write('\n')
  sys.stdout.flush()
  writer.close()

解释: sys.stdout.write()向缓冲区中写入内容, sys.stdout.flush()强制输出缓冲区的内容, 同时缓冲区被清空, '\r'的意思是回车, '\n'的意思是换行

猜你喜欢

转载自blog.csdn.net/weixin_42561002/article/details/87966252