This content originally appeared on DEV Community and was authored by IO_Node
Look at this bad boy I cooked up to extract a folder location from an error handling XD
def extract_cwd(data):
import re
match = re.search(r'File "(.*?\.py)", line \d+, in <module>', data)
if match:
print(f"Current Working Directory (CWD): {match.group(1)}")
else:
print("CWD not found in the traceback string.")
try:
crash
except Exception as e:
from traceback import format_exc
extract_cwd(format_exc())
# Output - :> Current Working Directory (CWD): path/to/script
I also made a smaller version using subprocess, just change cd to pwd if on linux
def extract():
from subprocess import run
return run("cd", shell=True, check=True, capture_output=True, text=True, encoding='utf-8')
That is all, thanks for tuning in.
This content originally appeared on DEV Community and was authored by IO_Node
IO_Node | Sciencx (2025-11-25T02:50:20+00:00) Back with another cancerous code block to share. Retrieved from https://www.scien.cx/2025/11/25/back-with-another-cancerous-code-block-to-share/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.