I'm trying to use the subprocess module in visual sutdio code but I keep getting an error. Here is the code:

import subprocess
subprocess.run("dir") 

or

import subprocess
subprocess.run("dir","/p")

and the error is:

Traceback (most recent call last):
  File "e:\Dropbox (Personal)\My Python\external\extrprg.py", line 2, in <module>
    subprocess.run("dir")
  File "E:\Users\klo\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 472, in run
    with Popen(*popenargs, **kwargs) as process:
  File "E:\Users\klo\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "E:\Users\klo\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 1178, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

I'd expect python to run dir and give me a list of the folders in the directory

1 Answers

0
Hai Vu On

dir is a command in cmd.exe, which means you want to do:

subprocess.run(['cmd.exe', '/c', 'dir'])