Restoring Support for Running Python with Read-Only Source Files on Windows

That’s right restoring support for running Python with read-only source files.

Now, if you’ve never encountered this issue before, let me paint you a picture: imagine you’re working on some code that involves modifying existing files or creating new ones. You save your changes and run the script, only to be met with an error message saying “Permission denied” or something similar.

At first, you might think there’s a problem with your permissions or file system settings. But if you check those things and they seem fine, what gives? Well, it turns out that Python on Windows has been broken in this regard for years until recently, when some kind soul stepped up to fix the issue (thanks, Nick Coghlan!).

So how do we go about restoring support for running Python with read-only source files on Windows? It’s actually pretty simple: just backdate your original source file by a few seconds or minutes. That way, when you run your script again, it will think that the file has changed and force a rewrite of the pyc (compiled bytecode) file.

Here’s an example command to do this in PowerShell:

# This script is used to backdate a source file in order to force a rewrite of the pyc (compiled bytecode) file when running a script again.

# Set the variable $file to the name of the source file that needs to be backdated.
$file = "my_script.py"

# Get the current date and time and subtract 10 seconds from it.
$date = Get-Date -Second 10

# Use the Set-ItemProperty cmdlet to change the LastWriteTime property of the source file to the backdated date and time.
Set-ItemProperty $file -Name LastWriteTime $date

This sets the last write time of `my_script.py` to be ten seconds in the future (relative to your current system time). When you run your script again, it will think that the file has changed and rewrite the pyc file accordingly.

And there you have it a simple solution to a long-standing problem! Of course, if you’re using some kind of version control system or other tool to manage your code, this might not be necessary (since those tools typically handle these issues for you). But if you’re working on Windows and encountering permission errors when running Python scripts with read-only source files, give this a try!

SICORPS