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"])
Answer from Czaporka on Stack OverflowHow subprocess run() works?
os.popen vs subprocess.run for simple commands
About 13 years ago, the older, deprecated per-os popen2/popen3/popen4 calls were removed, and os.popen() was implemented in terms of subprocess.Popen (just like subprocess.run is).:
https://github.com/python/cpython/commit/c2f93dc2e42b48a20578599407b0bb51a6663d09#diff-405b29928f2a3ae216e45afe9b5d0c60
So, I don't think the current os.popen() is deprecated anymore (I can't see any indication that it is; that was for the older versions which were removed).
Therefore, I think you can safely use it if you want. But, keep in mind that the popen() concept was pretty Unix specific, and isn't obvious to everyone that it's running a subprocess, whereas that should be fairly obvious from subprocess.run().
You could consider making a dictionary of keyword args (that you re-use), and passing that to subprocess.run(), if it's just the length of the calling lines that is concerning you:
runargs = {'shell': True, 'capture_output': True, 'text': True }
output = subprocess.run('<command>', **runargs).stdout More on reddit.com How do you keep a subprocess running after the python script ends on Windows?
subprocess.run: simple but powerful lib to execute external processes
Videos
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"])
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())