There are several ways to do this:

A simple way is using the os module:

import os
os.system("ls -l")

More complex things can be achieved with the subprocess module: for example:

import subprocess
test = subprocess.Popen(["ping","-W","2","-c", "1", "192.168.1.70"], stdout=subprocess.PIPE)
output = test.communicate()[0]
Answer from Uku Loskit on Stack Overflow
🌐
Python
docs.python.org › 3 › using › cmdline.html
1. Command line and environment — Python 3.14.4 documentation
python -m timeit -s "setup here" "benchmarked code here" python -m timeit -h # for details · Raises an auditing event cpython.run_module with argument module-name. ... Changed in version 3.1: Supply the package name to run a __main__ submodule. Changed in version 3.4: namespace packages are also supported ... Read commands from standard input (sys.stdin). If standard input is a terminal, -i is implied.
🌐
Real Python
realpython.com › terminal-commands
The Terminal: First Steps and Useful Commands for Python Developers – Real Python
February 2, 2026 - The terminal provides Python developers with direct control over their operating system through text commands. Instead of clicking through menus, you type commands to navigate folders, run scripts, install packages, and manage version control.
🌐
iO Flood
ioflood.com › blog › python-terminal-commands
Python Terminal Commands: Reference Guide
November 21, 2023 - Python terminal commands are a set of instructions that allow you to interact with your Python environment directly from your terminal. They enable you to execute Python scripts, manage Python packages, and much more.
🌐
Stanford CS
cs.stanford.edu › people › nick › py › python-command.html
Command Line
Select the "Open PowerShell window here" menu option to create a terminal starting in that folder. In either case you can use the commands "cd" and "ls" and "pwd" to examine what files are there and change directories. It's handy to measure how many seconds it takes to run a command. On most systems the time command does this (wordcount.py is a CS106A example from the later weeks): $ time python3 wordcount.py alice-book.txt ...
🌐
Flexiple
flexiple.com › python › python-commands
Python Commands List with Example - Flexiple - Flexiple
Variables are assigned using =, and arithmetic operations use operators like +, -, *, and /. The len() function returns the length of an object. input() reads a line from the input, converted into a string. Execute break to exit a loop before its normal termination. Use continue to skip the rest of the loop's body and immediately retest its condition. The python3 command initiates the Python interpreter in its version 3.x.
🌐
Real Python
realpython.com › run-python-scripts
How to Run Your Python Scripts and Code – Real Python
February 25, 2026 - The python command’s -m option runs Python modules by searching sys.path rather than requiring file paths. IDEs like PyCharm and code editors like Visual Studio Code provide built-in options to run scripts from the environment interface. To get the most out of this tutorial, you should know the basics of working with your operating system’s terminal ...
Find elsewhere
🌐
Medium
medium.com › @huzaifazahoor654 › 10-terminal-commands-every-python-dev-should-know-a75f801d08e2
10 Terminal Commands Every Python Dev Should Know | by Huzaifa Zahoor | Medium
June 4, 2025 - Python venv command isolates project dependencies, keeping our workspace clean. python -m venv myenv source myenv/bin/activate # On Windows: myenv\Scripts\activate · This creates and activates a virtual environment named myenv. Unlike global installations, Python terminal tricks like venv prevent version clashes, making it a Python productivity command.
🌐
Kinsta®
kinsta.com › home › resource center › blog › python › 20+ essential python commands you should know
20+ Essential Python Commands You Should Know
December 15, 2023 - On Linux, you have loads of different options depending on the distro you use, but the command “Ctrl + Alt + T” typically triggers the default terminal in your system. Now, you should have a window similar to the one shown below: ... Once you’ve got your CLI open, it’s time to dive into the top shell commands that will make your life as a Python developer much easier.
🌐
Quora
quora.com › How-do-I-run-terminal-commands-in-Python
How to run terminal commands in Python - Quora
If you are talking about ‘.py’ files then you can run them by simply pasting the file name in the terminal by writing “python ./filename enter or python3 ./filename” and then press enter then the python will automatically interpreted and run the program. And if u are asking for just running python then type python in command line or terminal.
🌐
Lancaster University
lancaster.ac.uk › staff › drummonn › PHYS281 › demo-python-terminal
The Python terminal - PHYS281
Within a terminal window (e.g., a Powershell terminal on Windows, or a terminal session within VS Code) you enter a regular Python terminal session by typing python and hitting Enter. You should see something like: Python 3.7.2 (default, Dec 29 2018, 06:19:36) [GCC 7.3.0] :: Anaconda, Inc. on linux Type "help", "copyright", "credits" or "license" for more information. >>> where the >>> is the command prompt starting the command line, i.e., the line that you input commands onto.
🌐
Reddit
reddit.com › r/python › python's many command-line utilities
r/Python on Reddit: Python's many command-line utilities
June 3, 2024 -

Python 3.12 comes bundled with 50 command-line tools.

For example, python -m webbrowser http://example.com opens a web browser, python -m sqlite3 launches a sqlite prompt, and python -m ast my_file.py shows the abstract syntax tree for a given Python file.

I've dug into each of them and categorized them based on their purpose and how useful they are.

Python's many command-line tools

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.

🌐
GeeksforGeeks
geeksforgeeks.org › python › executing-shell-commands-with-python
Executing Shell Commands with Python - GeeksforGeeks
February 14, 2026 - You can give more arguments to the Popen function Object() , like shell=True, which will make the command run in a separate shell. ... Example: Here the system() method is used to execute the pwd shell script using Python.
🌐
Luketudge
luketudge.github.io › introduction-to-programming › command_line.html
The command line — Introduction to Programming with Python
The command line will ‘echo back’ ... Python programs from the command line as well as from Spyder. To do this, simply type python, followed by the name of the Python program that you want to run....
🌐
Python.org
discuss.python.org › python help
How to run Python Terminal - Python Help - Discussions on Python.org
December 17, 2024 - I am using Windows operating machine. In start menu I found “Python 3.12.7 (64 bit)” But when I type python-v I am not able to get the python version. I think I am missing packages maybe. Kindly have a look at the atta…
🌐
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 - This is why it's also called the command line. To access the terminal on Windows, hit the Windows logo + R, type cmd, and press Enter. To access the terminal on Ubuntu, hit Ctrl + Alt + T. Python is an interpreted language.
🌐
DEV Community
dev.to › petercour › python-as-terminal-commands-26ii
Python as terminal commands - DEV Community
July 25, 2019 - This then outputs the numbers. Now you can use the alias command to create custom commands that run this python command · alias forloop='python -c "for i in range(1,10): print(i)"' Then in your terminal · # forloop · You can store these commands in your .bashrc file.
🌐
OpenTechSchool
opentechschool.github.io › python-beginners › en › getting_started.html
Getting started — Introduction to Programming with Python
There are in fact many ways to do this; the first one to learn is to interact with python’s interpreter, using your operating system’s (OS) console. A console (or ‘terminal’, or ‘command prompt’) is a textual way to interact with your OS, just as the ‘desktop’, in conjunction ...
🌐
SwCarpentry
swcarpentry.github.io › python-novice-inflammation › 12-cmdline.html
Programming with Python: Command-Line Programs
November 10, 2023 - When you see a $ in front of a command that tells you to run that command in the shell rather than the Python interpreter. This program does exactly what we want - it prints the average inflammation per patient for a given file. $ python ../code/readings_04.py --mean inflammation-01.csv