I attempted to run this simple program:
import os
import pygame
pygame.init()
font = pygame.font.Font('font.ttf', 20)
pygame.quit()
os.remove('font.ttf')
Pygame uses the font.ttf
file. But when it closes, it shouldn't use it anymore. So I should be able to remove the file. But it seems that os
can't delete it (an error says that the file is used by another process).
When I remove the font = ...
line, everything works perfectly. So, I conclude that the font file is still used, even if pygame
is quit by the use of quit()
.
Is this a bug? Have I missed something in the documentation? I have also tried this to see if pygame.quit()
runs in another thread which needs time to process - but the error still occurs:
...
import time
ok = False
while not ok:
time.sleep(1) # retry every second
try:
os.remove('font.ttf')
ok = True
except:
print('Error')
print('Success')
Call pygame. quit() to shut down pygame (this includes closing the window) Call sys. exit() to shut down the program (this exits the infinite loop)
The pygame. quit() function is sort of the opposite of the pygame. init() function: it runs code that deactivates the Pygame library. Your programs should always call pygame. quit() before they call sys.
You can always initialize individual modules manually, but pygame. init() initialize all imported pygame modules is a convenient way to get everything started. The init() functions for individual modules will raise exceptions when they fail.
All font file formats supported by FreeType can be rendered by pygame. freetype , namely TTF , Type1, CFF , OpenType, SFNT , PCF , FNT , BDF , PFR and Type42 fonts.
The problem here is that for whatever reason, despite using the pygame quitting method, it does not close the file handlers that it has created. In this case, you are giving it the font file name, then it opens the file, but it does not close the file after it is done.
A workaround to this problem is to give it a file handler, instead of a file name. Then, after you are done with pygame, you can close the file handler yourself.
import os
import pygame
# Make file handler
f = open('font.ttf', "r")
pygame.init()
# Give it the file handler instead
font = pygame.font.Font(f, 20)
pygame.quit()
# Close the handler after you are done
f.close()
# Works! (Tested on my machine)
os.remove('font.ttf')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With