@@ -473,6 +473,11 @@ def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,
473473 TemporaryFile = NamedTemporaryFile
474474
475475else :
476+ # Is the O_TMPFILE flag available and does it work?
477+ # The flag is set to False if os.open(dir, os.O_TMPFILE) raises an
478+ # IsADirectoryError exception
479+ _O_TMPFILE_WORKS = hasattr (_os , 'O_TMPFILE' )
480+
476481 def TemporaryFile (mode = 'w+b' , buffering = - 1 , encoding = None ,
477482 newline = None , suffix = "" , prefix = template ,
478483 dir = None ):
@@ -488,11 +493,32 @@ def TemporaryFile(mode='w+b', buffering=-1, encoding=None,
488493 Returns an object with a file-like interface. The file has no
489494 name, and will cease to exist when it is closed.
490495 """
496+ global _O_TMPFILE_WORKS
491497
492498 if dir is None :
493499 dir = gettempdir ()
494500
495501 flags = _bin_openflags
502+ if _O_TMPFILE_WORKS :
503+ try :
504+ flags2 = (flags | _os .O_TMPFILE ) & ~ _os .O_CREAT
505+ fd = _os .open (dir , flags2 , 0o600 )
506+ except IsADirectoryError :
507+ # Linux kernel older than 3.11 ignores O_TMPFILE flag.
508+ # Set flag to None to not try again.
509+ _O_TMPFILE_WORKS = False
510+ except OSError :
511+ # The filesystem of the directory does not support O_TMPFILE.
512+ # For example, OSError(95, 'Operation not supported').
513+ pass
514+ else :
515+ try :
516+ return _io .open (fd , mode , buffering = buffering ,
517+ newline = newline , encoding = encoding )
518+ except :
519+ _os .close (fd )
520+ raise
521+ # Fallback to _mkstemp_inner().
496522
497523 (fd , name ) = _mkstemp_inner (dir , prefix , suffix , flags )
498524 try :
0 commit comments