How to use subprocess.run method in python?

Question:

I wanted to run external programs using python but I receive an error saying I don’t have the file

the code I wrote:

import subprocess

subprocess.run(["ls", "-l"])

Output:

Traceback (most recent call last):
  File "C:UsershahandesktopPythonpmain.py", line 3, in <module>
    subprocess.run(["ls", "-l"])
  File "C:UsershahanAppDataLocalProgramsPythonPython310libsubprocess.py", line 501, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:UsershahanAppDataLocalProgramsPythonPython310libsubprocess.py", line 969, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:UsershahanAppDataLocalProgramsPythonPython310libsubprocess.py", line 1438, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

I expected it to return the files in that directory

Answers:

The stack trace suggests you’re using Windows as the operating system. ls not something that you will typically find on a Windows machine unless using something like CygWin.

Instead, try one of these options:

# use python's standard library function instead of invoking a subprocess
import os
os.listdir()
# invoke cmd and call the `dir` command
import subprocess
subprocess.run(["cmd", "/c", "dir"])
# invoke PowerShell and call the `ls` command, which is actually an alias for `Get-ChildItem`
import subprocess
subprocess.run(["powershell", "-c", "ls"])
Answered By: Czaporka

ls is not a Windows command. The windows analogue is dir, so you could do something like

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

However, if you’re really just trying to list a directory it would be much better (and portable) to use something like os.listdir()

import os
os.listdir()

or pathlib

from pathlib import Path
list(Path().iterdir())
Answered By: David
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.