Python 3 subprocess module throws error running “dir” on Windows

后端 未结 3 772
清歌不尽
清歌不尽 2021-01-06 22:58

This simple program in Python 3 throws errors. What could be the reason? This problem arose after I installed/reinstalled Python 3.5/3.6. Also

相关标签:
3条回答
  • 2021-01-06 23:10

    In addition to @grundic

    It's not an executable, but built-in to the shell. [...]

    If you really want to execute cmd built in commands, you have to execute cmd.exe /c COMMAND_HERE in your case:

    import subprocess 
    out = subprocess.check_output(['cmd.exe', '/c', 'dir'])
    

    /c means that cmd.exe closes after execution

    0 讨论(0)
  • 2021-01-06 23:12

    It seems that "dir" is not in your path. I do not know the full path of this executable on Windows but maybe you should replace dir by c:\windwos\system\dir

    Or a best solution would be to use functions in the os modules to list directories:

    os.listdir(path)
    
    0 讨论(0)
  • 2021-01-06 23:28

    It's not an executable, but built-in to the shell. Python subprocess module can't find it, so you got an error.

    If you would like to play with subprocess module, use some existing binary, e.g. python, notepad or ping. In case you need to list folder content, please use os.listdir or os.walk.

    0 讨论(0)
提交回复
热议问题