Use subprocess.run:

import subprocess

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

Another common way is os.system but you shouldn't use it because it is unsafe if any parts of the command come from outside your program or can contain spaces or other special characters, also subprocess.run is generally more flexible (you can get the stdout, stderr, the "real" status code, better error handling, etc.). Even the documentation for os.system recommends using subprocess instead.

On Python 3.4 and earlier, use subprocess.call instead of .run:

subprocess.call(["ls", "-l"])
Answer from David Cournapeau on Stack Overflow
Top answer
1 of 16
5977

Use subprocess.run:

import subprocess

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

Another common way is os.system but you shouldn't use it because it is unsafe if any parts of the command come from outside your program or can contain spaces or other special characters, also subprocess.run is generally more flexible (you can get the stdout, stderr, the "real" status code, better error handling, etc.). Even the documentation for os.system recommends using subprocess instead.

On Python 3.4 and earlier, use subprocess.call instead of .run:

subprocess.call(["ls", "-l"])
2 of 16
3677

Here is a summary of ways to call external programs, including their advantages and disadvantages:

  1. os.system passes the command and arguments to your system's shell. This is nice because you can actually run multiple commands at once in this manner and set up pipes and input/output redirection. For example:

    os.system("some_command < input_file | another_command > output_file")
    

    However, while this is convenient, you have to manually handle the escaping of shell characters such as spaces, et cetera. On the other hand, this also lets you run commands which are simply shell commands and not actually external programs.

  2. os.popen will do the same thing as os.system except that it gives you a file-like object that you can use to access standard input/output for that process. There are 3 other variants of popen that all handle the i/o slightly differently. If you pass everything as a string, then your command is passed to the shell; if you pass them as a list then you don't need to worry about escaping anything. Example:

    print(os.popen("ls -l").read())
    
  3. subprocess.Popen. This is intended as a replacement for os.popen, but has the downside of being slightly more complicated by virtue of being so comprehensive. For example, you'd say:

    print(subprocess.Popen("echo Hello World", shell=True, stdout=subprocess.PIPE).stdout.read())
    

    instead of

    print(os.popen("echo Hello World").read())
    

    but it is nice to have all of the options there in one unified class instead of 4 different popen functions. See the documentation.

  4. subprocess.call. This is basically just like the Popen class and takes all of the same arguments, but it simply waits until the command completes and gives you the return code. For example:

    return_code = subprocess.call("echo Hello World", shell=True)
    
  5. subprocess.run. Python 3.5+ only. Similar to the above but even more flexible and returns a CompletedProcess object when the command finishes executing.

  6. os.fork, os.exec, os.spawn are similar to their C language counterparts, but I don't recommend using them directly.

The subprocess module should probably be what you use.

Finally, please be aware that for all methods where you pass the final command to be executed by the shell as a string and you are responsible for escaping it. There are serious security implications if any part of the string that you pass can not be fully trusted. For example, if a user is entering some/any part of the string. If you are unsure, only use these methods with constants. To give you a hint of the implications consider this code:

print(subprocess.Popen("echo %s " % user_input, stdout=PIPE).stdout.read())

and imagine that the user enters something "my mama didnt love me && rm -rf /" which could erase the whole filesystem.

🌐
GeeksforGeeks
geeksforgeeks.org › python › executing-shell-commands-with-python
Executing Shell Commands with Python - GeeksforGeeks
February 14, 2026 - Example: Here the system() method is used to execute the pwd shell script using Python. run() is more flexible and quicker approach to run shell scripts, utilise the Popen function. ... The os module in Python includes functionality to communicate with the operating system. It is one of the standard utility modules of Python. It also offers a convenient way to use operating system-dependent features, shell commands can be executed using the system() method in the os module.
🌐
Real Python
realpython.com › run-python-scripts
How to Run Your Python Scripts and Code – Real Python
February 25, 2026 - Unix systems require executable permissions and a shebang line like #!/usr/bin/env python3 to run scripts directly as programs. The python command’s -m option runs Python modules by searching sys.path rather than requiring file paths.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-system-command-os-subprocess-call
Python os.system() vs subprocess: Run System Commands | DigitalOcean
March 18, 2026 - Python’s subprocess module gives you full control over running system commands, from simple one-liners to complex pipelines with real-time output streaming. For new projects, use subprocess.run() as your default. It handles output capture, error checking, and timeouts in a single function call.
🌐
Python
docs.python.org › 3 › using › cmdline.html
1. Command line and environment — Python 3.14.6 documentation
Execute the Python code in command. command can be one or more statements separated by newlines, with significant leading whitespace as in normal module code. If this option is given, the first element of sys.argv will be "-c" and the current directory will be added to the start of sys.path (allowing modules in that directory to be imported as top level modules). Raises an auditing event cpython.run_command with argument command.
🌐
Python
docs.python.org › 3 › library › subprocess.html
subprocess — Subprocess management
April 7, 2026 - Run command with arguments. Wait for command to complete. If the return code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute.
🌐
Agr0 Hacks Stuff
agrohacksstuff.io › posts › os-commands-with-python
OS Commands with Python | Agr0 Hacks Stuff
September 1, 2023 - This is similar to the system function, but instead of echoing the output to STDOUT of the calling shell, this will read the output as if it were a file handler (more specifically os._wrap_close, but it has access to an IO stream so read() will work with it), so you should treat it as such in python. ... I won’t bother getting into some of the legacy methods, but as of this writing the “preferred” method is to use subprocess.run().
🌐
Stack Abuse
stackabuse.com › executing-shell-commands-with-python
Executing Shell Commands with Python
January 6, 2023 - In your Terminal, run this file with using the following command, and you should see the corresponding output: $ python3 echo_adelle.py Hello from the other side!
Find elsewhere
🌐
Python Engineer
python-engineer.com › posts › python-execute-system-command
How to execute a Program or System Command from Python - Python Engineer
It runs the command described by args. Note that args must be a List of Strings, and not one single String with the whole command. The run function can take various optional arguments. More information can be found here. Note: In Python 3.4 and earlier, use subprocess.call() instead of .run():
🌐
Janakiev
janakiev.com › blog › python-shell-commands
How to Execute Shell Commands with Python - njanakiev
April 22, 2019 - A common thing to do, especially for a sysadmin, is to execute shell commands. But what usually will end up in a bash or batch file, can be also done in Python. You’ll learn here how to do just that with the os and subprocess modules. The first and the most straight forward approach to run a shell command is by using os.system():
🌐
freeCodeCamp
freecodecamp.org › news › run-python-script-how-to-execute-python-shell-commands-in-terminal
Run Python Script – How to Execute Python Shell Commands in the Terminal
July 14, 2022 - C:\Users\Suchandra Datta>python Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>print("hello world!") The interactive shell is also called REPL which stands for read, evaluate, print, loop. It'll read each command, evaluate and execute it, print the output for that command if any, and continue this same process repeatedly until you quit the shell.
🌐
Martin Heinz
martinheinz.dev › blog › 98
The Right Way to Run Shell Commands From Python | Martin Heinz | Personal Website & Blog
June 5, 2023 - General rule of thumb should be to use native functions instead of directly calling other programs or OS commands. So, first let's look at the native Python options: pathlib - If you need to create or delete file/directory; check if file exists; change permissions; etc., there's absolutely no reason to run system commands, just use pathlib, it has everything you need.
🌐
Thomas Stringer
trstringer.com › python-external-commands
Running External Commands in Python (Shell or Otherwise) | Thomas Stringer
April 6, 2025 - Which is essentially running /bin/sh -c sleep 60. You’re passing a single string sleep to the -c param of /bin/sh which causes the error. 60 is not contained in the command parameter. So we should instead do: ... One final note about string vs list of strings for the args. Let’s say you aren’t using a shell but for whatever reason you really want to do one long string. Python provides shlex.split to split the string with “shell-like syntax”. Our first example can be fixed if we do this instead:
🌐
OneUptime
oneuptime.com › home › blog › how to execute system commands from python
How to Execute System Commands from Python
January 25, 2026 - import subprocess # Send input to a command result = subprocess.run( ['grep', 'error'], input='line 1\nerror found\nline 3', capture_output=True, text=True ) print(result.stdout) # error found · import subprocess # For commands that need interaction, use Popen with communicate() process = subprocess.Popen( ['python'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) # Send Python code as input stdout, stderr = process.communicate(input='print("Hello from subprocess")\n') print(stdout) # Hello from subprocess
🌐
Python.org
discuss.python.org › python help
Run a Python file in Command Prompt - Python Help - Discussions on Python.org
December 21, 2023 - How to run a Python file in Windows Command Prompt using the imput command?
🌐
vteams
vteams.com › blog › how-to-run-a-python-script-in-terminal
How to Run a Python Script in Terminal Step by Step Guide
April 7, 2025 - To ace the process of how to run a python script in terminal, you’ll need to follow these fundamental steps: If you’re using a Linux or macOS system, you can usually find a terminal application in your applications or through a system search. Commonly used open terminal python include the GNOME Terminal, Konsole, and macOS’s Terminal. On Windows, you can use the Command Prompt or PowerShell.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-run-a-python-script
How to Run a Python Script - GeeksforGeeks
To run a Python script in Terminal from the command line, navigate to the script's directory and use the python script_name.py command. Redirecting output involves using the > symbol followed by a file name to capture the script's output in a file.
Published   October 2, 2025
🌐
Python
docs.python.org › 3 › faq › windows.html
Python on Windows FAQ — Python 3.14.6 documentation
On Windows, the standard Python installer already associates the .py extension with a file type (Python.File) and gives that file type an open command that runs the interpreter (D:\Program Files\Python\python.exe "%1" %*).
🌐
Aguaclara
aguaclara.github.io › aguaclara_tutorial › python › python-in-command-line.html
Running Python in the Command Line — AguaClara Tutorial v0.1.0 documentation
Need a refresher? See Basic Commands · Enter python, followed by a space, followed by the name of the file. Let’s say we have a script called foo.py containing this line: ... What this does is run the main body of the script: the lines which are not in functions.