pythonwindowscmdsubprocess

How to run CMD commands e.g. whoami and dir with python subprocess.run on Windows


I have this code: which is just a snippet of a larger application


    import subprocess

    print(subprocess.run(["dir"],text=True,capture_output=True))

Which is just a snippet of a larger application.

Which should output something around the lines of:


    04/09/2025  01:46 PM    <DIR>          random
    04/09/2025  01:46 PM    <DIR>          something else
    04/15/2025  11:56 AM    <DIR>          files

Instead I get this yucky error which I have shortened because it is very long:


    FileNotFoundError: [WinError 2] The system cannot find the file specified

Thank you in advance.


Solution

  • Have you tried to add the argument shell=True?

    print(subprocess.run("dir", text=True, capture_output=True, shell=True))
    

    shell=True is an argument that tells Python to run the command through the shell (i.e., cmd.exe on Windows), which knows what a dir cmd is.