Reputation: 675
I wrote a simple Python (3.2) script to download a series of files. It gets the job done, but the first print statement that comes before the try block doesn't execute before the file download begins. I expected to see "Downloading 1...", then wait a couple minutes, and then it would print "SUCCESS!" or "FAILURE!" afterwards. However, this all happens simultaneously after the file has downloaded. It still prints in the right order (ie, "Downloading 1...SUCCESS!"), but I can't for the life of me figure out why it's hanging.
from urllib import request
for i in range(1,35):
url = "http://example.com/" + str(i) + ".mp4"
print("Downloading " + str(i) + "...", end='') #this doesn't happen until after the try
try:
resp = request.urlopen(url)
local = open(str(i) + '.mp4', 'wb')
local.write(resp.read())
local.close()
print("SUCCESS!")
except:
print("FAILURE!")
Upvotes: 2
Views: 74
Reputation:
This has nothing to do with the try
block. The output happens just fine, but it's buffered. Your terminal is most likely line-buffered, meaning you don't see output before the respective line is output completely. You can flush it explicitly: sys.stdout.flush()
.
Upvotes: 3
Reputation: 62938
The standard output is buffered by default, call sys.stdout.flush()
after print
s or run your script with python -u script.py
.
Upvotes: 2