2012-03-30 9 views
19

Sulla mia macchina macchina Linux ulimit -n1024. Questo codice:Come si chiudono i file da tempfile.mkstemp?

from tempfile import mkstemp 

for n in xrange(1024 + 1): 
    f, path = mkstemp()  

non riesce all'ultimo ciclo linea con:

Traceback (most recent call last): 
    File "utest.py", line 4, in <module> 
    File "/usr/lib/python2.7/tempfile.py", line 300, in mkstemp 
    File "/usr/lib/python2.7/tempfile.py", line 235, in _mkstemp_inner 
OSError: [Errno 24] Too many open files: '/tmp/tmpc5W3CF' 
Error in sys.excepthook: 
Traceback (most recent call last): 
    File "/usr/lib/python2.7/dist-packages/apport_python_hook.py", line 64, in apport_excepthook 
ImportError: No module named fileutils 

Sembra che ho aperto a molti file - ma la type di f e path sono semplicemente int e così ho str non sono sicuro di come chiudere ogni file che ho aperto. Come si chiudono i file da tempfile.mkstemp?

risposta

13
import tempfile 
import os 
for idx in xrange(1024 + 1): 
    outfd, outsock_path = tempfile.mkstemp() 
    outsock = os.fdopen(outfd,'w') 
    outsock.close() 
+8

Tanto per spiegare un po '. mkstemp() restituisce un descrittore di file unix, quindi per lavorarci è necessario aprirlo usando fdopen o usare la funzione os close: os.close() – turtlebender

+0

Grazie, @turtlebender. – unutbu

22

Dal mkstemp() restituisce un descrittore di file RAW, è possibile utilizzare os.close():

import os 
from tempfile import mkstemp 

for n in xrange(1024 + 1): 
    f, path = mkstemp() 
    # Do something with 'f'... 
    os.close(f) 
2

Usa os.close() per chiudere il descrittore di file:

import os 
from tempfile import mkstemp 

# Open a file 
fd, path = mkstemp() 

# Close opened file 
os.close(fd) 
Problemi correlati