diff --git a/src/PyodideWorker.js b/src/PyodideWorker.js index f0c024352..dbb882b51 100644 --- a/src/PyodideWorker.js +++ b/src/PyodideWorker.js @@ -381,12 +381,15 @@ const PyodideWorker = () => { await pyodide.runPythonAsync(` import basthon import builtins + import os # Save the original open function _original_open = builtins.open def _custom_open(filename, mode="r", *args, **kwargs): - if "w" in mode or "a" in mode: + if "x" in mode and os.path.exists(filename): + raise FileExistsError(f"File '{filename}' already exists") + if "w" in mode or "a" in mode or "x" in mode: class CustomFile: def __init__(self, filename): self.filename = filename @@ -400,6 +403,12 @@ const PyodideWorker = () => { def close(self): pass + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + return CustomFile(filename) else: return _original_open(filename, mode, *args, **kwargs) diff --git a/src/components/Editor/Runners/PythonRunner/PyodideRunner/VisualOutputPane.jsx b/src/components/Editor/Runners/PythonRunner/PyodideRunner/VisualOutputPane.jsx index 073d31f78..71c84c2d4 100644 --- a/src/components/Editor/Runners/PythonRunner/PyodideRunner/VisualOutputPane.jsx +++ b/src/components/Editor/Runners/PythonRunner/PyodideRunner/VisualOutputPane.jsx @@ -74,7 +74,7 @@ const VisualOutputPane = ({ visuals, setVisuals }) => { (item) => item.extension === extension && item.name === name ); let updatedContent; - if (content.mode === "w") { + if (content.mode === "w" || content.mode === "x") { updatedContent = content.content; } else if (content.mode === "a") { updatedContent = componentToUpdate.content + "\n" + content.content;