I’m new to python developing. I’m trying to write something in a file (tmp.addr2line) and run a shell command on this file. But when I compare the file used by my shell command and my just created file, they are different, the file used is smaller.
There is my code (the command run in subprocess.call is not the final one).
test = open("tmp.addr2line", "w")
for i in __coverage_information__:
test.write(i.address + "\n")
test.close
subprocess.call("wc tmp.addr2line", shell = True)
Return
268697 268698 2686976 tmp.addr2line
And if I run wc tmp.addr2line after my python script, I got:
271710 271710 2717100 tmp.addr2line
So lines are missing, and don’t know why. I hope you will be able to help me.
You are not closing your file. You need to call the close function:
Without the
()you are only referencing the function, not actually invoking it. Until you properly close the file, the write buffer is not being flushed, and you only see the partial write.You can use files as context managers in a
withstatement. When the block underneath thewithstatement is done, the file is closed automatically without you needing to callclose()at all:It’s best to avoid the
shell=Trueparameter where possible, use this instead: