Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use subprocess.run method in python?

Tags:

python

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

like image 653
YoussefElGamedZ07leka Avatar asked May 23 '26 07:05

YoussefElGamedZ07leka


2 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"])
like image 95
Czaporka Avatar answered May 24 '26 21:05

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())
like image 21
David Avatar answered May 24 '26 19:05

David