We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
pyomo.common.tempfiles.TempfileManager raises FileNotFoundError
I've recently started using pyomo.common.tempfiles.TempfileManager to set the temporary directory in a package, as in https://pyomo.readthedocs.io/en/stable/working_models.html#changing-the-temporary-directory. I was previously using TempfileManager from PyUtilib for about 4 years. 

My tests now fail. Here is some of the trace:

  File "/home/user/anaconda38/lib/python3.8/site-packages/pyomo/opt/base/solvers.py", line 571, in solve
    self._presolve(*args, **kwds)
  File "/home/user/anaconda38/lib/python3.8/site-packages/pyomo/solvers/plugins/solvers/CPLEX.py", line 349, in _presolve
    ILMLicensedSystemCallSolver._presolve(self, *args, **kwds)
  File "/home/user/anaconda38/lib/python3.8/site-packages/pyomo/opt/solver/shellcmd.py", line 197, in _presolve
    OptSolver._presolve(self, *args, **kwds)
  File "/home/user/anaconda38/lib/python3.8/site-packages/pyomo/opt/base/solvers.py", line 668, in _presolve
    self._convert_problem(args,
  File "/home/user/anaconda38/lib/python3.8/site-packages/pyomo/opt/base/solvers.py", line 738, in _convert_problem
    return convert_problem(args,
  File "/home/user/anaconda38/lib/python3.8/site-packages/pyomo/opt/base/convert.py", line 105, in convert_problem
    problem_files, symbol_map = converter.apply(*tmp, **tmpkw)
  File "/home/user/anaconda38/lib/python3.8/site-packages/pyomo/solvers/plugins/converter/model.py", line 72, in apply
    problem_filename = TempfileManager.\
  File "/home/user/anaconda38/lib/python3.8/site-packages/pyomo/common/tempfiles.py", line 67, in create_tempfile
    ans = tempfile.mkstemp(suffix=suffix, prefix=prefix, text=text, dir=dir)
  File "/home/user/anaconda38/lib/python3.8/tempfile.py", line 332, in mkstemp
    return _mkstemp_inner(dir, prefix, suffix, flags, output_type)
  File "/home/user/anaconda38/lib/python3.8/tempfile.py", line 250, in _mkstemp_inner
    fd = _os.open(file, flags, 0o600)
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmpc6s9g6hf/tmpjoxugx27.pyomo.lp'

If I run the tests individually on the commandline, then the FileNotFoundError does not occur.

If I run all the tests from a script, then the FileNotFoundError does occur.

If I run all the tests from the same script, but change the order of the tests, then the FileNotFoundError still occurs but during a different test.

Note that in all tests, I'm not acutally setting TempfileManager.tempdir. It appears in a method, but this method is not called during these tests. So just the import "from pyomo.common.tempfiles import TempfileManager" is being run.

Now if I change my code so that "TempfileManager.tempdir = None" is always called for each test, then the FileNotFoundError no longer occurs.

Can you help?

I'm using Python 3.8.5 from Anaconda, Pyomo 5.7.2 and Ubuntu 18.04 LTS.

Thanks,
Jason

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pyomo/common/tempfiles.py`
Content:
```
1 #  ___________________________________________________________________________
2 #
3 #  Pyomo: Python Optimization Modeling Objects
4 #  Copyright 2017 National Technology and Engineering Solutions of Sandia, LLC
5 #  Under the terms of Contract DE-NA0003525 with National Technology and
6 #  Engineering Solutions of Sandia, LLC, the U.S. Government retains certain
7 #  rights in this software.
8 #  This software is distributed under the 3-clause BSD License.
9 #  ___________________________________________________________________________
10 #
11 #  This module was originally developed as part of the PyUtilib project
12 #  Copyright (c) 2008 Sandia Corporation.
13 #  This software is distributed under the BSD License.
14 #  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
15 #  the U.S. Government retains certain rights in this software.
16 #  ___________________________________________________________________________
17 
18 import os
19 import time
20 import tempfile
21 import logging
22 import shutil
23 from pyomo.common.deprecation import deprecation_warning
24 try:
25     from pyutilib.component.config.tempfiles import (
26         TempfileManager as pyutilib_mngr
27     )
28 except ImportError:
29     pyutilib_mngr = None
30 
31 deletion_errors_are_fatal = True
32 
33 
34 class TempfileManagerClass:
35     """A class that manages temporary files."""
36 
37     tempdir = None
38 
39     def __init__(self, **kwds):
40         self._tempfiles = [[]]
41         self._ctr = -1
42 
43     def create_tempfile(self, suffix=None, prefix=None, text=False, dir=None):
44         """Create a unique temporary file
45 
46         Returns the absolute path of a temporary filename that is
47         guaranteed to be unique.  This function generates the file and
48         returns the filename.
49 
50         """
51         if suffix is None:
52             suffix = ''
53         if prefix is None:
54             prefix = 'tmp'
55         if dir is None:
56             dir = self.tempdir
57             if dir is None and pyutilib_mngr is not None:
58                 dir = pyutilib_mngr.tempdir
59                 if dir is not None:
60                     deprecation_warning(
61                         "The use of the PyUtilib TempfileManager.tempdir "
62                         "to specify the default location for Pyomo "
63                         "temporary files has been deprecated.  "
64                         "Please set TempfileManager.tempdir in "
65                         "pyomo.common.tempfiles", version='5.7.2')
66 
67         ans = tempfile.mkstemp(suffix=suffix, prefix=prefix, text=text, dir=dir)
68         ans = list(ans)
69         if not os.path.isabs(ans[1]):  #pragma:nocover
70             fname = os.path.join(dir, ans[1])
71         else:
72             fname = ans[1]
73         os.close(ans[0])
74         if self._ctr >= 0:
75             new_fname = os.path.join(dir, prefix + str(self._ctr) + suffix)
76             # Delete any file having the sequential name and then
77             # rename
78             if os.path.exists(new_fname):
79                 os.remove(new_fname)
80             shutil.move(fname, new_fname)
81             fname = new_fname
82             self._ctr += 1
83         self._tempfiles[-1].append(fname)
84         return fname
85 
86     def create_tempdir(self, suffix=None, prefix=None, dir=None):
87         """Create a unique temporary directory
88 
89         Returns the absolute path of a temporary directory that is
90         guaranteed to be unique.  This function generates the directory
91         and returns the directory name.
92 
93         """
94         if suffix is None:
95             suffix = ''
96         if prefix is None:
97             prefix = 'tmp'
98         if dir is None:
99             dir = self.tempdir
100             if dir is None and pyutilib_mngr is not None:
101                 dir = pyutilib_mngr.tempdir
102                 if dir is not None:
103                     deprecation_warning(
104                         "The use of the PyUtilib TempfileManager.tempdir "
105                         "to specify the default location for Pyomo "
106                         "temporary directories has been deprecated.  "
107                         "Please set TempfileManager.tempdir in "
108                         "pyomo.common.tempfiles", version='5.7.2')
109 
110         dirname = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=dir)
111         if self._ctr >= 0:
112             new_dirname = os.path.join(dir, prefix + str(self._ctr) + suffix)
113             # Delete any directory having the sequential name and then
114             # rename
115             if os.path.exists(new_dirname):
116                 shutil.rmtree(new_dirname)
117             shutil.move(dirname, new_dirname)
118             dirname = new_dirname
119             self._ctr += 1
120 
121         self._tempfiles[-1].append(dirname)
122         return dirname
123 
124     def add_tempfile(self, filename, exists=True):
125         """Declare this file to be temporary."""
126         tmp = os.path.abspath(filename)
127         if exists and not os.path.exists(tmp):
128             raise IOError("Temporary file does not exist: " + tmp)
129         self._tempfiles[-1].append(tmp)
130 
131     def clear_tempfiles(self, remove=True):
132         """Delete all temporary files."""
133         while len(self._tempfiles) > 1:
134             self.pop(remove)
135         self.pop(remove)
136 
137     def sequential_files(self, ctr=0):
138         """Start generating sequential files, using the specified counter"""
139         self._ctr = ctr
140 
141     def unique_files(self):
142         """Stop generating sequential files, using the specified counter"""
143         self._ctr = -1
144 
145     #
146     # Support "with" statements, where the pop automatically
147     # takes place on exit.
148     #
149     def push(self):
150         self._tempfiles.append([])
151         return self
152 
153     def __enter__(self):
154         self.push()
155 
156     def __exit__(self, type, value, traceback):
157         self.pop(remove=True)
158 
159     def pop(self, remove=True):
160         files = self._tempfiles.pop()
161         if remove:
162             for filename in files:
163                 if os.path.exists(filename):
164                     if os.path.isdir(filename):
165                         shutil.rmtree(
166                             filename,
167                             ignore_errors=not deletion_errors_are_fatal)
168                     else:
169                         try:
170                             os.remove(filename)
171                         except WindowsError:
172                             # Sometimes Windows doesn't release the
173                             # file lock immediately when the process
174                             # terminates.  If we get an error, wait a
175                             # second and try again.
176                             try:
177                                 time.sleep(1)
178                                 os.remove(filename)
179                             except WindowsError:
180                                 if deletion_errors_are_fatal:
181                                     raise
182                                 else:
183                                     # Failure to delete a tempfile
184                                     # should NOT be fatal
185                                     logger = logging.getLogger(__name__)
186                                     logger.warning("Unable to delete temporary "
187                                                    "file %s" % (filename,))
188 
189         if len(self._tempfiles) == 0:
190             self._tempfiles = [[]]
191 
192 TempfileManager = TempfileManagerClass()
193
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pyomo/common/tempfiles.py b/pyomo/common/tempfiles.py
--- a/pyomo/common/tempfiles.py
+++ b/pyomo/common/tempfiles.py
@@ -34,9 +34,8 @@
 class TempfileManagerClass:
     """A class that manages temporary files."""
 
-    tempdir = None
-
     def __init__(self, **kwds):
+        self.tempdir = None
         self._tempfiles = [[]]
         self._ctr = -1
 
@@ -189,4 +188,5 @@
         if len(self._tempfiles) == 0:
             self._tempfiles = [[]]
 
+
 TempfileManager = TempfileManagerClass()

{"golden_diff": "diff --git a/pyomo/common/tempfiles.py b/pyomo/common/tempfiles.py\n--- a/pyomo/common/tempfiles.py\n+++ b/pyomo/common/tempfiles.py\n@@ -34,9 +34,8 @@\n class TempfileManagerClass:\n     \"\"\"A class that manages temporary files.\"\"\"\n \n-    tempdir = None\n-\n     def __init__(self, **kwds):\n+        self.tempdir = None\n         self._tempfiles = [[]]\n         self._ctr = -1\n \n@@ -189,4 +188,5 @@\n         if len(self._tempfiles) == 0:\n             self._tempfiles = [[]]\n \n+\n TempfileManager = TempfileManagerClass()\n", "issue": "pyomo.common.tempfiles.TempfileManager raises FileNotFoundError\nI've recently started using pyomo.common.tempfiles.TempfileManager to set the temporary directory in a package, as in https://pyomo.readthedocs.io/en/stable/working_models.html#changing-the-temporary-directory. I was previously using TempfileManager from PyUtilib for about 4 years. \r\n\r\nMy tests now fail. Here is some of the trace:\r\n\r\n  File \"/home/user/anaconda38/lib/python3.8/site-packages/pyomo/opt/base/solvers.py\", line 571, in solve\r\n    self._presolve(*args, **kwds)\r\n  File \"/home/user/anaconda38/lib/python3.8/site-packages/pyomo/solvers/plugins/solvers/CPLEX.py\", line 349, in _presolve\r\n    ILMLicensedSystemCallSolver._presolve(self, *args, **kwds)\r\n  File \"/home/user/anaconda38/lib/python3.8/site-packages/pyomo/opt/solver/shellcmd.py\", line 197, in _presolve\r\n    OptSolver._presolve(self, *args, **kwds)\r\n  File \"/home/user/anaconda38/lib/python3.8/site-packages/pyomo/opt/base/solvers.py\", line 668, in _presolve\r\n    self._convert_problem(args,\r\n  File \"/home/user/anaconda38/lib/python3.8/site-packages/pyomo/opt/base/solvers.py\", line 738, in _convert_problem\r\n    return convert_problem(args,\r\n  File \"/home/user/anaconda38/lib/python3.8/site-packages/pyomo/opt/base/convert.py\", line 105, in convert_problem\r\n    problem_files, symbol_map = converter.apply(*tmp, **tmpkw)\r\n  File \"/home/user/anaconda38/lib/python3.8/site-packages/pyomo/solvers/plugins/converter/model.py\", line 72, in apply\r\n    problem_filename = TempfileManager.\\\r\n  File \"/home/user/anaconda38/lib/python3.8/site-packages/pyomo/common/tempfiles.py\", line 67, in create_tempfile\r\n    ans = tempfile.mkstemp(suffix=suffix, prefix=prefix, text=text, dir=dir)\r\n  File \"/home/user/anaconda38/lib/python3.8/tempfile.py\", line 332, in mkstemp\r\n    return _mkstemp_inner(dir, prefix, suffix, flags, output_type)\r\n  File \"/home/user/anaconda38/lib/python3.8/tempfile.py\", line 250, in _mkstemp_inner\r\n    fd = _os.open(file, flags, 0o600)\r\nFileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmpc6s9g6hf/tmpjoxugx27.pyomo.lp'\r\n\r\nIf I run the tests individually on the commandline, then the FileNotFoundError does not occur.\r\n\r\nIf I run all the tests from a script, then the FileNotFoundError does occur.\r\n\r\nIf I run all the tests from the same script, but change the order of the tests, then the FileNotFoundError still occurs but during a different test.\r\n\r\nNote that in all tests, I'm not acutally setting TempfileManager.tempdir. It appears in a method, but this method is not called during these tests. So just the import \"from pyomo.common.tempfiles import TempfileManager\" is being run.\r\n\r\nNow if I change my code so that \"TempfileManager.tempdir = None\" is always called for each test, then the FileNotFoundError no longer occurs.\r\n\r\nCan you help?\r\n\r\nI'm using Python 3.8.5 from Anaconda, Pyomo 5.7.2 and Ubuntu 18.04 LTS.\r\n\r\nThanks,\r\nJason\n", "before_files": [{"content": "#  ___________________________________________________________________________\n#\n#  Pyomo: Python Optimization Modeling Objects\n#  Copyright 2017 National Technology and Engineering Solutions of Sandia, LLC\n#  Under the terms of Contract DE-NA0003525 with National Technology and\n#  Engineering Solutions of Sandia, LLC, the U.S. Government retains certain\n#  rights in this software.\n#  This software is distributed under the 3-clause BSD License.\n#  ___________________________________________________________________________\n#\n#  This module was originally developed as part of the PyUtilib project\n#  Copyright (c) 2008 Sandia Corporation.\n#  This software is distributed under the BSD License.\n#  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n#  the U.S. Government retains certain rights in this software.\n#  ___________________________________________________________________________\n\nimport os\nimport time\nimport tempfile\nimport logging\nimport shutil\nfrom pyomo.common.deprecation import deprecation_warning\ntry:\n    from pyutilib.component.config.tempfiles import (\n        TempfileManager as pyutilib_mngr\n    )\nexcept ImportError:\n    pyutilib_mngr = None\n\ndeletion_errors_are_fatal = True\n\n\nclass TempfileManagerClass:\n    \"\"\"A class that manages temporary files.\"\"\"\n\n    tempdir = None\n\n    def __init__(self, **kwds):\n        self._tempfiles = [[]]\n        self._ctr = -1\n\n    def create_tempfile(self, suffix=None, prefix=None, text=False, dir=None):\n        \"\"\"Create a unique temporary file\n\n        Returns the absolute path of a temporary filename that is\n        guaranteed to be unique.  This function generates the file and\n        returns the filename.\n\n        \"\"\"\n        if suffix is None:\n            suffix = ''\n        if prefix is None:\n            prefix = 'tmp'\n        if dir is None:\n            dir = self.tempdir\n            if dir is None and pyutilib_mngr is not None:\n                dir = pyutilib_mngr.tempdir\n                if dir is not None:\n                    deprecation_warning(\n                        \"The use of the PyUtilib TempfileManager.tempdir \"\n                        \"to specify the default location for Pyomo \"\n                        \"temporary files has been deprecated.  \"\n                        \"Please set TempfileManager.tempdir in \"\n                        \"pyomo.common.tempfiles\", version='5.7.2')\n\n        ans = tempfile.mkstemp(suffix=suffix, prefix=prefix, text=text, dir=dir)\n        ans = list(ans)\n        if not os.path.isabs(ans[1]):  #pragma:nocover\n            fname = os.path.join(dir, ans[1])\n        else:\n            fname = ans[1]\n        os.close(ans[0])\n        if self._ctr >= 0:\n            new_fname = os.path.join(dir, prefix + str(self._ctr) + suffix)\n            # Delete any file having the sequential name and then\n            # rename\n            if os.path.exists(new_fname):\n                os.remove(new_fname)\n            shutil.move(fname, new_fname)\n            fname = new_fname\n            self._ctr += 1\n        self._tempfiles[-1].append(fname)\n        return fname\n\n    def create_tempdir(self, suffix=None, prefix=None, dir=None):\n        \"\"\"Create a unique temporary directory\n\n        Returns the absolute path of a temporary directory that is\n        guaranteed to be unique.  This function generates the directory\n        and returns the directory name.\n\n        \"\"\"\n        if suffix is None:\n            suffix = ''\n        if prefix is None:\n            prefix = 'tmp'\n        if dir is None:\n            dir = self.tempdir\n            if dir is None and pyutilib_mngr is not None:\n                dir = pyutilib_mngr.tempdir\n                if dir is not None:\n                    deprecation_warning(\n                        \"The use of the PyUtilib TempfileManager.tempdir \"\n                        \"to specify the default location for Pyomo \"\n                        \"temporary directories has been deprecated.  \"\n                        \"Please set TempfileManager.tempdir in \"\n                        \"pyomo.common.tempfiles\", version='5.7.2')\n\n        dirname = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=dir)\n        if self._ctr >= 0:\n            new_dirname = os.path.join(dir, prefix + str(self._ctr) + suffix)\n            # Delete any directory having the sequential name and then\n            # rename\n            if os.path.exists(new_dirname):\n                shutil.rmtree(new_dirname)\n            shutil.move(dirname, new_dirname)\n            dirname = new_dirname\n            self._ctr += 1\n\n        self._tempfiles[-1].append(dirname)\n        return dirname\n\n    def add_tempfile(self, filename, exists=True):\n        \"\"\"Declare this file to be temporary.\"\"\"\n        tmp = os.path.abspath(filename)\n        if exists and not os.path.exists(tmp):\n            raise IOError(\"Temporary file does not exist: \" + tmp)\n        self._tempfiles[-1].append(tmp)\n\n    def clear_tempfiles(self, remove=True):\n        \"\"\"Delete all temporary files.\"\"\"\n        while len(self._tempfiles) > 1:\n            self.pop(remove)\n        self.pop(remove)\n\n    def sequential_files(self, ctr=0):\n        \"\"\"Start generating sequential files, using the specified counter\"\"\"\n        self._ctr = ctr\n\n    def unique_files(self):\n        \"\"\"Stop generating sequential files, using the specified counter\"\"\"\n        self._ctr = -1\n\n    #\n    # Support \"with\" statements, where the pop automatically\n    # takes place on exit.\n    #\n    def push(self):\n        self._tempfiles.append([])\n        return self\n\n    def __enter__(self):\n        self.push()\n\n    def __exit__(self, type, value, traceback):\n        self.pop(remove=True)\n\n    def pop(self, remove=True):\n        files = self._tempfiles.pop()\n        if remove:\n            for filename in files:\n                if os.path.exists(filename):\n                    if os.path.isdir(filename):\n                        shutil.rmtree(\n                            filename,\n                            ignore_errors=not deletion_errors_are_fatal)\n                    else:\n                        try:\n                            os.remove(filename)\n                        except WindowsError:\n                            # Sometimes Windows doesn't release the\n                            # file lock immediately when the process\n                            # terminates.  If we get an error, wait a\n                            # second and try again.\n                            try:\n                                time.sleep(1)\n                                os.remove(filename)\n                            except WindowsError:\n                                if deletion_errors_are_fatal:\n                                    raise\n                                else:\n                                    # Failure to delete a tempfile\n                                    # should NOT be fatal\n                                    logger = logging.getLogger(__name__)\n                                    logger.warning(\"Unable to delete temporary \"\n                                                   \"file %s\" % (filename,))\n\n        if len(self._tempfiles) == 0:\n            self._tempfiles = [[]]\n\nTempfileManager = TempfileManagerClass()\n", "path": "pyomo/common/tempfiles.py"}], "after_files": [{"content": "#  ___________________________________________________________________________\n#\n#  Pyomo: Python Optimization Modeling Objects\n#  Copyright 2017 National Technology and Engineering Solutions of Sandia, LLC\n#  Under the terms of Contract DE-NA0003525 with National Technology and\n#  Engineering Solutions of Sandia, LLC, the U.S. Government retains certain\n#  rights in this software.\n#  This software is distributed under the 3-clause BSD License.\n#  ___________________________________________________________________________\n#\n#  This module was originally developed as part of the PyUtilib project\n#  Copyright (c) 2008 Sandia Corporation.\n#  This software is distributed under the BSD License.\n#  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n#  the U.S. Government retains certain rights in this software.\n#  ___________________________________________________________________________\n\nimport os\nimport time\nimport tempfile\nimport logging\nimport shutil\nfrom pyomo.common.deprecation import deprecation_warning\ntry:\n    from pyutilib.component.config.tempfiles import (\n        TempfileManager as pyutilib_mngr\n    )\nexcept ImportError:\n    pyutilib_mngr = None\n\ndeletion_errors_are_fatal = True\n\n\nclass TempfileManagerClass:\n    \"\"\"A class that manages temporary files.\"\"\"\n\n    def __init__(self, **kwds):\n        self.tempdir = None\n        self._tempfiles = [[]]\n        self._ctr = -1\n\n    def create_tempfile(self, suffix=None, prefix=None, text=False, dir=None):\n        \"\"\"Create a unique temporary file\n\n        Returns the absolute path of a temporary filename that is\n        guaranteed to be unique.  This function generates the file and\n        returns the filename.\n\n        \"\"\"\n        if suffix is None:\n            suffix = ''\n        if prefix is None:\n            prefix = 'tmp'\n        if dir is None:\n            dir = self.tempdir\n            if dir is None and pyutilib_mngr is not None:\n                dir = pyutilib_mngr.tempdir\n                if dir is not None:\n                    deprecation_warning(\n                        \"The use of the PyUtilib TempfileManager.tempdir \"\n                        \"to specify the default location for Pyomo \"\n                        \"temporary files has been deprecated.  \"\n                        \"Please set TempfileManager.tempdir in \"\n                        \"pyomo.common.tempfiles\", version='5.7.2')\n\n        ans = tempfile.mkstemp(suffix=suffix, prefix=prefix, text=text, dir=dir)\n        ans = list(ans)\n        if not os.path.isabs(ans[1]):  #pragma:nocover\n            fname = os.path.join(dir, ans[1])\n        else:\n            fname = ans[1]\n        os.close(ans[0])\n        if self._ctr >= 0:\n            new_fname = os.path.join(dir, prefix + str(self._ctr) + suffix)\n            # Delete any file having the sequential name and then\n            # rename\n            if os.path.exists(new_fname):\n                os.remove(new_fname)\n            shutil.move(fname, new_fname)\n            fname = new_fname\n            self._ctr += 1\n        self._tempfiles[-1].append(fname)\n        return fname\n\n    def create_tempdir(self, suffix=None, prefix=None, dir=None):\n        \"\"\"Create a unique temporary directory\n\n        Returns the absolute path of a temporary directory that is\n        guaranteed to be unique.  This function generates the directory\n        and returns the directory name.\n\n        \"\"\"\n        if suffix is None:\n            suffix = ''\n        if prefix is None:\n            prefix = 'tmp'\n        if dir is None:\n            dir = self.tempdir\n            if dir is None and pyutilib_mngr is not None:\n                dir = pyutilib_mngr.tempdir\n                if dir is not None:\n                    deprecation_warning(\n                        \"The use of the PyUtilib TempfileManager.tempdir \"\n                        \"to specify the default location for Pyomo \"\n                        \"temporary directories has been deprecated.  \"\n                        \"Please set TempfileManager.tempdir in \"\n                        \"pyomo.common.tempfiles\", version='5.7.2')\n\n        dirname = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=dir)\n        if self._ctr >= 0:\n            new_dirname = os.path.join(dir, prefix + str(self._ctr) + suffix)\n            # Delete any directory having the sequential name and then\n            # rename\n            if os.path.exists(new_dirname):\n                shutil.rmtree(new_dirname)\n            shutil.move(dirname, new_dirname)\n            dirname = new_dirname\n            self._ctr += 1\n\n        self._tempfiles[-1].append(dirname)\n        return dirname\n\n    def add_tempfile(self, filename, exists=True):\n        \"\"\"Declare this file to be temporary.\"\"\"\n        tmp = os.path.abspath(filename)\n        if exists and not os.path.exists(tmp):\n            raise IOError(\"Temporary file does not exist: \" + tmp)\n        self._tempfiles[-1].append(tmp)\n\n    def clear_tempfiles(self, remove=True):\n        \"\"\"Delete all temporary files.\"\"\"\n        while len(self._tempfiles) > 1:\n            self.pop(remove)\n        self.pop(remove)\n\n    def sequential_files(self, ctr=0):\n        \"\"\"Start generating sequential files, using the specified counter\"\"\"\n        self._ctr = ctr\n\n    def unique_files(self):\n        \"\"\"Stop generating sequential files, using the specified counter\"\"\"\n        self._ctr = -1\n\n    #\n    # Support \"with\" statements, where the pop automatically\n    # takes place on exit.\n    #\n    def push(self):\n        self._tempfiles.append([])\n        return self\n\n    def __enter__(self):\n        self.push()\n\n    def __exit__(self, type, value, traceback):\n        self.pop(remove=True)\n\n    def pop(self, remove=True):\n        files = self._tempfiles.pop()\n        if remove:\n            for filename in files:\n                if os.path.exists(filename):\n                    if os.path.isdir(filename):\n                        shutil.rmtree(\n                            filename,\n                            ignore_errors=not deletion_errors_are_fatal)\n                    else:\n                        try:\n                            os.remove(filename)\n                        except WindowsError:\n                            # Sometimes Windows doesn't release the\n                            # file lock immediately when the process\n                            # terminates.  If we get an error, wait a\n                            # second and try again.\n                            try:\n                                time.sleep(1)\n                                os.remove(filename)\n                            except WindowsError:\n                                if deletion_errors_are_fatal:\n                                    raise\n                                else:\n                                    # Failure to delete a tempfile\n                                    # should NOT be fatal\n                                    logger = logging.getLogger(__name__)\n                                    logger.warning(\"Unable to delete temporary \"\n                                                   \"file %s\" % (filename,))\n\n        if len(self._tempfiles) == 0:\n            self._tempfiles = [[]]\n\n\nTempfileManager = TempfileManagerClass()\n", "path": "pyomo/common/tempfiles.py"}]}