Reputation: 565
Hopefully someone can help me out. This seems like a very simple question that I just can't find the answer to. I am trying to create a tempfile, and then using this same tempfile, I'd like to write into it using the dd command. And then open that same file and time the time it takes to read the file.
I'm not sure why, but this is the error I'm getting. TypeError: coercing to Unicode: need string or buffer, instance found. I think it's because I've got the same file open at the same time, but not sure. Any ideas?
Here's the code:
import time
import tempfile
import subprocess
import argparse
def readfile(size, block_size, path):
with tempfile.NamedTemporaryFile(prefix='iospeeds-', dir=path, delete=True) as tf:
cmd = ['dd', 'if=/dev/zero', 'of={}'.format(tf), 'bs={}'.format(block_size), 'count={}'.format(size/block_size)]
subprocess.call(cmd, stderr=subprocess.STDOUT)
start_time = time.time()
with open(tf, 'rb') as read_file:
end_time = time.time()
total_time = start_time - end_time
print total_time
return total_time
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--size', type=int, default=1048576)
parser.add_argument('--block-size', type=int, default=4096)
parser.add_argument('--path', default='./')
return parser.parse_args()
def main():
args=parse_args()
size = args.size
block_size = args.block_size
path = args.path
readfile(size, block_size, path)
if __name__ == "__main__":
main()
Here's the Traceback:
Traceback (most recent call last):
File "./rd.py", line 38, in <module>
main()
File "./rd.py", line 35, in main
readfile(size, block_size, path)
File "./rd.py", line 14, in readfile
with open(tf, 'rb') as read_file:
Thanks!
Upvotes: 0
Views: 1095
Reputation: 28302
You're trying to open a file with a file type in the name spot, basically you're trying to do open(file, 'rb')
instead of open(filename, 'rb')
. Try:
with open(tf.name, 'rb') as read_file:
Upvotes: 1