Skip to content

Issue with temporary files on Windows: PermissionError: [Errno 13] Permission denied #77

@vdmitriyev

Description

@vdmitriyev

What happens:

  • Issue with temporary files on Windows: PermissionError: [Errno 13] Permission denied

Why it happens:

The PermissionError: [Errno 13] Permission denied when dealing with tempfile.NamedTemporaryFile in Pythoncode snippet is a common issue, especially on Windows, and it boils down to how file handles and permissions are managed. Basically it means, this temporary file cannot be used by any other processes/functions, until is will be closed. Thus, before calling copy_to_runtime the file MUST be closed and then MANUALLY deleted upon finish.

Code hotfix (must be applied in session_base.py):

def _run_code() -> ConsoleOutput:
	import tempfile
	import uuid
	from pathlib import Path

	self.install(libraries)
	try:
		with tempfile.NamedTemporaryFile(
			delete=False, # Set delete=False so we can access it after the 'with' block
			suffix=f".{self.language_handler.file_extension}",
			mode="w", # Open in text mode for writing strings directly
			encoding="utf-8"
			) as code_file:
				code_file.write(code)
				temp_file_path = code_file.name # Store the name before the file is closed
		
		code_dest_file = Path(self.config.workdir) / f"{uuid.uuid4().hex}.{self.language_handler.file_extension}"
		self.copy_to_runtime(temp_file_path, str(code_dest_file))

		commands = self.language_handler.get_execution_commands(str(code_dest_file))
		return self.execute_commands(
			commands,
			workdir=self.config.workdir,
		)
	finally:
		# Clean up the temporary file if it was created
		if temp_file_path and Path(temp_file_path).exists():
			import os
			os.remove(temp_file_path)

P.S. I could also prepare a PR with the fix, here is just an issue for others to know that problem exists

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions