python / cpython

The Python programming language
https://www.python.org
Other
63.37k stars 30.33k forks source link

Windows compatibility issues: Access tempfile.NamedTemporaryFile is not possible through the browser until the file is closed. #112277

Open ahaoboy opened 11 months ago

ahaoboy commented 11 months ago

Bug report

Bug description:

Create a temporary file, write html content, invoke the flush function, then wait for user input. At this point, the file exists and can be opened via VSCode or cat, but cannot be accessed through a web browser.

import tempfile
import sys
import webbrowser

f = tempfile.NamedTemporaryFile(
    prefix="web_config",
    suffix=".html",
    delete=True,
    # delete_on_close=False,
    # delete_on_close=True,
    delete_on_close=False,
    mode="w",
)
f.write("<h1>aaaa</h1>")
f.flush()

print(f.name)

# if you close first, then it's ok
# f.close()

fileurl = "file://" + f.name
print(fileurl)

webbrowser.open(fileurl)
sys.stdin.readline()

# f.close()

After test with two win11 pc and edge/chrome/firefox, I find some interesting things

You can also open it by copying and pasting the fileurl or by right-clicking with the mouse. The result is the same.

chrome/edge image firefox is waiting forever and do nothing image

CPython versions tested on:

3.12

Operating systems tested on:

Windows

ericvsmith commented 11 months ago

You haven't provided enough information here to debug this: how does the browser fail?

I suspect this is an "open for sharing" problem on Windows. You might be able to use the opener argument to open() to create a file that has the sharing permissions you're after. But you'll have to know what sharing access the browser is requesting. And then it probably wouldn't work with NamedTemporaryFile (I haven't delved into the details to see if you can specify an opener with NamedTemporaryFile).

ahaoboy commented 11 months ago

You haven't provided enough information here to debug this: how does the browser fail?

I suspect this is an "open for sharing" problem on Windows. You might be able to use the opener argument to open() to create a file that has the sharing permissions you're after. But you'll have to know what sharing access the browser is requesting. And then it probably wouldn't work with NamedTemporaryFile (I haven't delved into the details to see if you can specify an opener with NamedTemporaryFile).

I updated the bug report.