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:\Users\hahan\desktop\Pythonp\main.py", line 3, in <module>
subprocess.run(["ls", "-l"])
File "C:\Users\hahan\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 501, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\Users\hahan\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 969, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\hahan\AppData\Local\Programs\Python\Python310\lib\subprocess.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
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With