import re, chardet, subprocess


def shell(cmd='', stdout=None, stderr=None, timeout=None):
    match stdout:
        case 'NULL' | 'Null' | 'null':
            stdoutCh = subprocess.DEVNULL
        case _:
            stdoutCh = subprocess.PIPE
    match stderr:
        case 'NULL' | 'Null' | 'null':
            stderrCh = subprocess.DEVNULL
        case _:
            stderrCh = subprocess.PIPE
    try:
        result = subprocess.run(cmd, shell=True, stdout=stdoutCh, stderr=stderrCh, timeout=timeout)
        stdoutContent = ''
        stderrContent = ''
        if result.stdout:
            stdoutContent = result.stdout.decode(chardet.detect(result.stdout)["encoding"] or 'UTF-8')
        if result.stderr:
            stderrContent = result.stderr.decode(chardet.detect(result.stderr)["encoding"] or 'UTF-8')
        return {
            "code": result.returncode, "stdout": stdoutContent, "stderr": stderrContent
        }
    except subprocess.TimeoutExpired:
        return {
            "code": 1,
            "stdout": '',
            "stderr": 'Execution timeout.'
        }


if __name__ == '__main__':
    # Example. Normal.
    print(shell('ping www.taobao.com'))
    # Example. No STDOUT.
    print(shell('ping www.taobao.com', stdout='NULL'))
    # Example. No STDERR.
    print(shell('ping www.taobao.com', stderr='NULL'))
    # Example. No STDOUT and STDERR.
    print(shell('ping www.taobao.com', stdout='NULL', stderr='NULL'))
    # Example. With Timeout.
    print(shell('ping www.taobao.com', timeout=3))
    # Example. With Timeout Not.
    print(shell('ping www.taobao.com', timeout=8))
    # Example. Curl.
    print(shell('curl "https://www.baidu.com/"'))
    # Example. Unknown Command.
    print(shell('busybox ls'))
