|
// retoor <retoor@molodetz.nl>
|
|
|
|
import "tempfile" for TempFile, NamedTemporaryFile, TemporaryDirectory
|
|
import "pathlib" for Path
|
|
|
|
System.print("=== TempFile Module Demo ===\n")
|
|
|
|
System.print("--- Utility Functions ---")
|
|
System.print("Temp directory: %(TempFile.gettempdir())")
|
|
System.print("Temp prefix: %(TempFile.gettempprefix())")
|
|
|
|
System.print("\n--- mktemp (name only, no file created) ---")
|
|
var name = TempFile.mktemp(".txt", "demo_")
|
|
System.print("Generated name: %(name)")
|
|
System.print("File exists: %(Path.new(name).exists())")
|
|
|
|
System.print("\n--- mkstemp (creates file atomically) ---")
|
|
var path = TempFile.mkstemp(".dat", "demo_")
|
|
System.print("Created file: %(path)")
|
|
System.print("File exists: %(Path.new(path).exists())")
|
|
Path.new(path).unlink()
|
|
|
|
System.print("\n--- mkdtemp (creates directory) ---")
|
|
var dir = TempFile.mkdtemp("_work", "demo_")
|
|
System.print("Created directory: %(dir)")
|
|
System.print("Is directory: %(Path.new(dir).isDir())")
|
|
Path.new(dir).rmdir()
|
|
|
|
System.print("\n--- NamedTemporaryFile ---")
|
|
var tmp = NamedTemporaryFile.new(".txt", "demo_")
|
|
System.print("Temp file: %(tmp.name)")
|
|
tmp.write("Hello from tempfile module!")
|
|
System.print("Content: %(tmp.read())")
|
|
System.print("Auto-delete: %(tmp.delete)")
|
|
tmp.close()
|
|
System.print("Deleted after close: %(!(Path.new(tmp.name).exists()))")
|
|
|
|
System.print("\n--- NamedTemporaryFile.use (context manager) ---")
|
|
NamedTemporaryFile.new(".log").use {|f|
|
|
f.write("Log entry: operation completed")
|
|
System.print("Inside use block: %(f.read())")
|
|
}
|
|
System.print("Automatically cleaned up after use block")
|
|
|
|
System.print("\n--- TemporaryDirectory ---")
|
|
var tmpDir = TemporaryDirectory.new("_session", "demo_")
|
|
System.print("Temp dir: %(tmpDir.name)")
|
|
System.print("Is directory: %(tmpDir.path.isDir())")
|
|
tmpDir.cleanup()
|
|
System.print("Deleted after cleanup: %(!(Path.new(tmpDir.name).exists()))")
|
|
|
|
System.print("\n--- TemporaryDirectory.use (context manager) ---")
|
|
TemporaryDirectory.new().use {|d|
|
|
System.print("Working in: %(d.name)")
|
|
Path.new(d.name + "/data.txt").writeText("temporary data")
|
|
System.print("Created file inside temp dir")
|
|
}
|
|
System.print("Automatically cleaned up with all contents")
|
|
|
|
System.print("\n=== Done ===")
|