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
5973

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
3674

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 - Shells in the operating system can be either a CLI (Command Line Interface) or a GUI (Graphical User Interface) based on the functionality and basic operation of the device. The Python subprocess module can be used to run new programs or applications. Getting the input/output/error pipes and exit codes of different commands is also helpful. ... Example: Here the subprocess.Popen() method is used to execute the echo shell script using Python.
Discussions

Execute shell commands in Python - Unix & Linux Stack Exchange
By default call will try to open ... the shell=True is set. It also looks like that in Python 3.5 call is replaced with run ... Generic POSIX code should probably call decode() with charset from LC_CTYPE environment variable. ... The first command simply writes to a file. You wouldn't execute that as a ... More on unix.stackexchange.com
๐ŸŒ unix.stackexchange.com
The Right Way to Run Shell Commands From Python
Well, there's a good list of modules to use above other alternatives pathlib, tempfile, and shutil you should always look at first before invoking subprocesses. However, later the articule has a few things that bug me. First, one should never mention shell=True without explaining the huge problems it can cause. By default, you shouldn't use shell=True unless you have an explicit explanation as to why it's a good idea, and why is it needed. Saying shlex.split is an alternative to that is also not good. Another insidious issue is... the examples are all... misleading. You should never invoke ls -la from a Python program. And much less pipe the output to awk. Precisely when you are explaining people to use pathlib and shutil! It may appear a minor point, but this is important. Python is a great replacement to using a traditional shell and text processing tools, and it leads to more robust and portable scripts... if you use it properly! I do agree that subprocess has missing batteries, and sh... is a clever thing, but I wouldn't recommend it. (What I miss in subprocess is having it some logging support, making check=True the default, and a few other quality of life improvements...) More on reddit.com
๐ŸŒ r/coding
5
12
June 5, 2023
Calling a System/Shell command with Python - Using the Subprocess module
Hey Everyone ๐Ÿป, Pretty simple tutorial here on how to send commands to the shell using the subprocess module. I made this tutorial because when I started learning Python, this module was a big help in creating scripts that helped me automate tasks. Unfortunately, before I found out about the subprocess module I was just using os.system and ran into a lot of problems. Looking forward to everyone's feedback! More on reddit.com
๐ŸŒ r/Python
6
13
February 23, 2021
How do I run shell commands in python?
I could only understand the title. Guess I'm not far enough in my studies. Probably should stop slacking. Anyway, anyone correct me if I'm wrong, but this was the simplest and most recommended method. (idk if it varies on version and os, but for reference, Python 3.7.x, Windows) import subprocess subprocess.run(["ls", "-l"]) I have a command line tool that I was trying to import into my script. Turned out it was easier and better (performance wise, in my case) to just subprocess.run('le stuff in ze cmd') (sadly, I learned this was a bad candidate for multiprocessing =/) Although now I've resorted to 'paraphrasing', if you will, one of the features of the tool I was trying to import. But that's a story for never. More on reddit.com
๐ŸŒ r/learnpython
5
3
October 27, 2019
๐ŸŒ
Janakiev
janakiev.com โ€บ blog โ€บ python-shell-commands
How to Execute Shell Commands with Python - njanakiev
April 22, 2019 - You have seen now how to run external commands in Python. The most effective way is to use the subprocess module with all the functionality it offers. Most notably, you should consider using subprocess.run. For a short and quick script you might just want to use the os.system() or os.popen() functions. If you have any questions, feel free to leave them in the comments below. There are also other useful libraries that support shell commands in Python, like plumbum, sh, psutils and pexpect.
Top answer
1 of 6
154

You can use os.system(), like this:

import os
os.system('ls')

Or in your case:

os.system('echo 1 > /proc/sys/net/ipv4/ip_forward')
os.system('iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 8080')

Better yet, you can use subprocess's call, it is safer, more powerful and likely faster:

from subprocess import call
call('echo "I like potatos"', shell=True)

Or, without invoking shell:

call(['echo', 'I like potatos'])

If you want to capture the output, one way of doing it is like this:

import subprocess
cmd = ['echo', 'I like potatos']
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

o, e = proc.communicate()

print('Output: ' + o.decode('ascii'))
print('Error: '  + e.decode('ascii'))
print('code: ' + str(proc.returncode))

I highly recommend setting a timeout in communicate, and also to capture the exceptions you can get when calling it. This is a very error-prone code, so you should expect errors to happen and handle them accordingly.

https://docs.python.org/3/library/subprocess.html

2 of 6
33

The first command simply writes to a file. You wouldn't execute that as a shell command because python can read and write to files without the help of a shell:

with open('/proc/sys/net/ipv4/ip_forward', 'w') as f:
    f.write("1")

The iptables command is something you may want to execute externally. The best way to do this is to use the subprocess module.

import subprocess
subprocess.check_call(['iptables', '-t', 'nat', '-A',
                       'PREROUTING', '-p', 'tcp', 
                       '--destination-port', '80',
                       '-j', 'REDIRECT', '--to-port', '8080'])

Note that this method also does not use a shell, which is unnecessary overhead.

๐ŸŒ
Reddit
reddit.com โ€บ r/coding โ€บ the right way to run shell commands from python
r/coding on Reddit: The Right Way to Run Shell Commands From Python
June 5, 2023 - I mostly disagree with this, as someone thatโ€™s written alot of shell. Itโ€™s too easy to write bad shell and standardizing on Python will have more consistent results for all but the most trivial of scripts. Calling a System/Shell command with Python - Using the Subprocess module
๐ŸŒ
Martin Heinz
martinheinz.dev โ€บ blog โ€บ 98
The Right Way to Run Shell Commands From Python | Martin Heinz | Personal Website & Blog
June 5, 2023 - Most of the remaining functions in os module are direct interface to OS (or C language) API, e.g. os.dup, os.splice, os.mkfifo, os.execv, os.fork, etc. If you need to use all of those, then I'm not sure whether Python is the right language for the task... A second - little better - options that we have in Python is subprocess module: import subprocess p = subprocess.run('ls -l', shell=True, check=True, capture_output=True, encoding='utf-8') # 'p' is instance of 'CompletedProcess(args='ls -la', returncode=0)' print(f'Command {p.args} exited with {p.returncode} code, output: \n{p.stdout}') # Command ls -la exited with 0 code # total 36 # drwxrwxr-x 2 martin martin 4096 apr 22 12:53 .
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ subprocess.html
subprocess โ€” Subprocess management
3 weeks ago - The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence. On POSIX with shell=True, the shell defaults to /bin/sh. If args is a string, the string specifies the command to execute through the shell.
Find elsewhere
๐ŸŒ
YouTube
youtube.com โ€บ learnedu
Executing Shell Commands with Python - YouTube
In this video I show you how to execute Shell or Terminal window commands from within a python program. This builds upon my two previous videos which are lin...
Published ย  July 26, 2023
Views ย  489
๐ŸŒ
Analytics Vidhya
analyticsvidhya.com โ€บ home โ€บ executing shell commands with python
Here's How You Can Execute Shell Commands in Python
January 16, 2024 - While the `subprocess` module provides a more sophisticated way to execute shell commands, the `os.system` function offers a simple and direct approach. This function allows you to run shell commands directly from Python, without the need to create subprocesses or handle input/output streams explicitly.
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ executing-shell-commands-with-python
Executing Shell Commands with Python
January 6, 2023 - The os.system() function executes a command, prints any output of the command to the console, and returns the exit code of the command. If we would like more fine grained control of a shell command's input and output in Python, we should use the subprocess module.
๐ŸŒ
Linux Handbook
linuxhandbook.com โ€บ execute-shell-command-python
How to Execute Bash Shell Commands with Python
June 28, 2022 - A slightly better way of running shell commands in Python is using the subprocess module. If you want to run a shell command without any options and arguments, you can call subprocess like this: ... The call method will execute the shell command.
๐ŸŒ
ZetCode
zetcode.com โ€บ python โ€บ exec-command
Python exec - executing shell commands and programs in Python
January 29, 2024 - #!/usr/bin/python import subprocess output = subprocess.run(['node', '--version'], text=True, capture_output=True) print(f'Node version: {output.stdout.strip()}') The example uses subprocess module to get the version of Node. output = subprocess.run(['node', '--version'], text=True, capture_output=True) The run executes the command, waits for command to complete, and returns a CompletedProcess instance.
๐ŸŒ
CodeFatherTech
codefather.tech โ€บ home โ€บ blog โ€บ how to execute a shell command in python [step-by-step]
How to Execute a Shell Command in Python [Step-by-Step]
December 8, 2024 - There are multiple ways to execute a shell command in Python. The simplest ones use the os.system and os.popen functions.
๐ŸŒ
Thomas Stringer
trstringer.com โ€บ python-external-commands
Running External Commands in Python (Shell or Otherwise) | Thomas Stringer
April 6, 2025 - Oftentimes we just open up our terminal and type things in to run them, and now we want our Python code to do the same. The short answer is that you only need a shell if you require shell syntax and/or are running multiple commands at once. For instance, if you want your Python code to run the executable my_cool_bin with a few arguments, you donโ€™t need a shell.
๐ŸŒ
TestDriven.io
testdriven.io โ€บ tips โ€บ ba47cde8-bb52-469b-b1d5-c0bb6c2b5493
Tips and Tricks - Python - execute shell commands in subprocess | TestDriven.io
Use the subprocess module to spawn new processes ยท https://docs.python.org/3/library/subprocess.html#subprocess.Popen
๐ŸŒ
DEV Community
dev.to โ€บ divshekhar โ€บ python-subprocess-execute-shell-commands-1bl2
Python Execute Shell Command: Python Subprocess โ€“ Execute Shell Commands - DEV Community
May 23, 2023 - The subprocess.run() function was added in Python 3.5 and it is recommended to use the run() function to execute the shell commands in the python program.
๐ŸŒ
iO Flood
ioflood.com โ€บ blog โ€บ python-run-shell-command
Using Python to Run Shell Commands
December 7, 2023 - Running shell commands using Python is a powerful feature that can significantly enhance your scripts. Weโ€™ve explored how to use the subprocess.run() function to execute commands, capture their output, and handle errors.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ scripting โ€บ how to execute a bash command in a python script
How to Execute a Bash Command in a Python Script | Baeldung on Linux
February 19, 2025 - ... $ ./subprocess_run.py "sudo dnf list | grep -i iperf" iperf3.x86_64 3.9-11.el9 @appstream iperf3.i686 3.9-11.el9 appstream ยท The input command to the Python script is sudo dnf list | grep -i iperf.
๐ŸŒ
GitHub
github.com โ€บ Apakottur โ€บ shpyx
GitHub - Apakottur/shpyx: Run shell commands in Python
For example, on non Windows systems, fcntl is used to configure the subprocess to always be incorruptible (which means one can CTRL-C out of any command). The call to subprocess.Popen uses shell=True when the input to run is a string (to support shell logic like bash piping). This means that an actual system shell is being created, and the subprocess has the permissions of the main Python process.
Starred by 17 users
Forked by 2 users
Languages ย  Python 100.0% | Python 100.0%