Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a Python os.PathLike object from a NamedTemporaryFile using the tempfile module?

Tags:

python

I'm trying to call a Python (3.8) function using the pdfkit library that requires a list of file objects. I only have strings, so I need to write each string to a temporary file that I will delete after the function returns. I can roll my own solution for this, but it would be much more convenient (and portable) if I could use the tempfile module for this. Unfortunately, when I wrap each string with a NamedTemporaryFile, my function complains with a TypeError that I must supply something that is os.PathLike, not _TemporaryFileWrapper.

Is it possible to get something from the tempfile module that is suitable for this purpose?

from tempfile import NamedTemporaryFile
import pdfkit

the_files = []

for html in my_html_strings:
    tmp_file = NamedTemporaryFile(mode='w', suffix='.html')
    tmp_file.write(html)
    the_files.append(tmp_file)

pdf_data = pdfkit.from_file(the_files, False) # raises

And the stack trace:

  File "...", line 68, in my_code
    pdf_data = pdfkit.from_file(section_files, False, options=opts)
  File ".../lib/python3.8/site-packages/pdfkit/api.py", line 46, in from_file
    r = PDFKit(input, 'file', options=options, toc=toc, cover=cover, css=css,
  File ".../lib/python3.8/site-packages/pdfkit/pdfkit.py", line 41, in __init__
    self.source = Source(url_or_file, type_)
  File ".../lib/python3.8/site-packages/pdfkit/source.py", line 12, in __init__
    self.checkFiles()
  File ".../lib/python3.8/site-packages/pdfkit/source.py", line 28, in checkFiles
    if not os.path.exists(path):
  File "/usr/lib/python3.8/genericpath.py", line 19, in exists
    os.stat(path)
TypeError: stat: path should be string, bytes, os.PathLike or integer, not _TemporaryFileWrapper
like image 685
RTF Avatar asked Jun 18 '26 12:06

RTF


1 Answers

You don't need a PathLike. You just need a string representing the file path. For a NamedTemporaryFile, that string is its name attribute:

namedtempfile.name

Almost everything that takes an os.PathLike is supposed to take a plain string too.

If for some weird reason you find yourself in a situation where you really need a PathLike and a string actually doesn't work, you can wrap the string in a pathlib.Path:

import pathlib
pathlike = pathlib.Path(nametempfile.name)

This is not such a situation.

like image 90
user2357112 supports Monica Avatar answered Jun 20 '26 01:06

user2357112 supports Monica