mktemp() is deprecated and not secure. So I try to upgrade it to mkstemp().
class TestUtils:
@contextmanager
def temp_dir(self):
tmp = tempfile.mkdtemp()
try:
yield tmp
finally:
shutil.rmtree(tmp)
@contextmanager
def temp_file(self):
with self.temp_dir() as tmp:
yield tempfile.mktemp(dir=tmp)
class CsvTest(PandasOnSparkTestCase, TestUtils):
def setUp(self):
self.tmp_dir = tempfile.mkdtemp(prefix=CsvTest.__name__)
def tearDown(self):
shutil.rmtree(self.tmp_dir, ignore_errors=True)
@contextmanager
def csv_file(self, csv):
with self.temp_file() as tmp:
with open(tmp, "w") as f:
f.write(csv)
yield tmp
When I change yield tempfile.mktemp(dir=tmp)
to yield tempfile.mkstemp(dir=tmp)
it returns a tuple.
And when I change it to yield tempfile.NamedTemporaryFile(dir=tmp, delete=False)
I got TypeError: expected str, bytes or os.PathLike object, not _TemporaryFileWrapper
What is the right way to do this?
CodePudding user response:
From the documentation:
mkstemp()
returns a tuple containing an OS-level handle to an open file (as would be returned byos.open()
) and the absolute pathname of that file, in that order.
mktemp()
just returns the pathname. So if you want to be compatible with mktemp
, use
yield tempfile.mktemp(dir=tmp)[1]
to return the pathname.
CodePudding user response:
try to use
yield tempfile.mktemp(dir=tmp)[1]