DEV Community

IO_Node
IO_Node

Posted on

Back with another cancerous code block to share

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
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

That is all, thanks for tuning in.

Top comments (0)