The exec command replaces the currently running process with a new one, so if you have an exec in a list of commands to run, as soon as exec is run, nothing else will run. So you're replacing 'bash -c \"exec bash; MY_COMMAND; exec bash\" ' with bash, and then nothing after the exec bash is running. Try this instead:

os.system("gnome-terminal -e 'bash -c \"MY_COMMAND\" '")

or if you need a terminal to stay open, try this:

os.system("gnome-terminal -e 'bash -c \"MY_COMMAND; sleep 1000000\" '")

of if you want the terminal to stay open and be in a bash shell, try this:

os.system("gnome-terminal -e 'bash -c \"MY_COMMAND; bash\" '")
Answer from Christopher Shroba on Stack Overflow
🌐
Ask Ubuntu
askubuntu.com › questions › 1441006 › opening-a-new-terminal-from-python-script-and-running-commands
Opening a new terminal from python script and running commands - Ask Ubuntu
November 16, 2022 - I've included my code below. I would like to be able to launch a bash script as part of this python script below which launches a new terminal at a specific directory. The command I'd like to run is 'ls' once the new terminal is launched.
Discussions

Open terminal and write in it from python script
Hello everyone, I am trying to use the python API CORE ( Common Open Research Emulator) to create a simulation. I am at the point that I want to open a terminal of a node and write some ubuntu terminal command from the python script. I am able to open the terminal, but once I start to write ... More on discuss.python.org
🌐 discuss.python.org
2
0
November 15, 2023
bash - How can I make a script that opens terminal window, executes commands in it and remains open on Scientific Linux? - Unix & Linux Stack Exchange
I'm working in a remote server that uses Scientific Linux (version=7.6 (Nitrogen)). I did a simple web application in Python3, and I found myself constantly opening a Mate Terminal (though, any te... More on unix.stackexchange.com
🌐 unix.stackexchange.com
open a terminal from python - Stack Overflow
I'm developing a program that has a button. When pressed, I want to open a terminal that runs: sudo apt-get update I'm using: os.system("gnome-terminal -e 'sudo apt-get update'") This works fin... More on stackoverflow.com
🌐 stackoverflow.com
shell - Execute terminal command from python in new terminal window? - Stack Overflow
This worked to open a new terminal window and run a script in it. The script could then run another Python program. For example: hostnamectl; # tested on Operating System: Debian GNU/Linux 12 (bookworm) Kernel: Linux 6.1.0-20-amd64 Architecture: x86-64 python --version Python 3.11.2; # tested ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/learnpython › how to use python to open a terminal window and run command-line-based software in it?
r/learnpython on Reddit: how to use python to open a terminal window and run command-line-based software in it?
February 9, 2022 -

The following python code will run a command-line-based software (shown in the "cmd" string) in the background which takes a long time.

May I ask how to use python to open a new terminal window and run the same command in it, so that the main python code can move on to process other things without being blocked here?

Thanks.

cmd = 'las2txt64 -i point_cloud_data.las -o output.csv -parse xyzRGBinrc -sep comma'

with open('output.txt', 'w') as f: 
    run_las = subprocess.Popen(
        cmd, 
        shell=True, 
        stderr=f, 
        text=True, 
    )

    run_las.wait()
🌐
GitHub
github.com › skywind3000 › terminal
GitHub - skywind3000/terminal: Open Terminal Window to execute command in Windows / Cygwin / Ubuntu / OS X · GitHub
Set the title of the terminal window (not available in some terminal). $ python terminal.py Usage: terminal.py [options] command [args ...] Execute program in a new terminal window Options: --version show program's vers
Starred by 55 users
Forked by 21 users
Languages   Python
🌐
Python.org
discuss.python.org › python help
Open terminal and write in it from python script - Python Help - Discussions on Python.org
November 15, 2023 - Hello everyone, I am trying to use the python API CORE ( Common Open Research Emulator) to create a simulation. I am at the point that I want to open a terminal of a node and write some ubuntu terminal command from the python script. I am able to open the terminal, but once I start to write the command lines with os.system function in python, these commands are executed in other terminal ( the main terminal), I did not understand why.
🌐
Delft Stack
delftstack.com › home › howto › python › python script to open terminal and run command linux
How to Create Python Script to Open a New Terminal and Run Commands in Linux | Delft Stack
February 2, 2024 - The gnome-terminal command launches a new gnome-terminal inside the Linux OS. The variable My_Cmmnd contents are sent as a Bash command to the new terminal to execute. The script executes the syntax and displays the desired output. ... The last example showed how to create a Python script to open a new terminal and run a command by storing it inside a variable.
Find elsewhere
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › community › general discussion
Open terminal with python - Raspberry Pi Forums
Tue Dec 10, 2019 12:41 pm Are you ... your python program after the GUI has loaded. so open the file with the following command ... sudo nano /etc/xdg/lxsession/LXDE-pi/autostart and add as the last line the following, were " /home/pi/your_script.py " is the path and file name ...
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › using the raspberry pi › beginners
How to open a new terminal and run commands in it - Raspberry Pi Forums
lxterminal -e mvn exec:exec then when mvn terminates then the lxterminal window will (should) close. As long as mvn is still running the lxterminal window will stay open. Kira the Koding Kitty, R.I.P. 8/3/24 ... Here is what worked for me. I am using "lxterminal" to execute the python scripts ...
🌐
Real Python
realpython.com › run-python-scripts
How to Run Your Python Scripts and Code – Real Python
February 25, 2026 - To start a Python interactive session, or REPL, open a command-line window, type in the python command, and then press Enter. These steps will take you into the Python interpreter, which looks something like the following: ... PS> python Python ...
🌐
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 - Executing a Python script within a terminal is an essential skill for every Python programmer. Whether you’re using Linux, Windows, or an integrated development environment like VSCode, the process is straightforward. You can run Python scripts as executables, call specific functions with command line arguments, and handle various scenarios effectively. To execute a Python script, first open a terminal, then navigate to the directory where the script is located, and finally, run the script using the ‘python’ command followed by the script’s name.
🌐
Quora
quora.com › How-do-I-run-terminal-commands-in-Python
How to run terminal commands in Python - Quora
Answer (1 of 2): [code]os.system(‘ ’) [/code]will run the shell script/command in the argument: output will be displayed, or can be redirected to a file. in Python 3.5 and up, [code]results = subprocess.run(‘ ’, capture_output=True) [/code]will run the shell script/command argu...
Top answer
1 of 4
54

There's no way to do this in general from a shell. What you have to do is run the terminal program itself, or some launcher program that does so for you. And the way to do that is different for each terminal program.

In some cases, os.startfile will do what you want, but this isn't going to be universal.

Also, note in general, you're going to actually need an absolute path to your script, because the new terminal window will be running a new shell and therefore won't necessarily have your same working directory. But I'll ignore that for the examples.


With Windows cmd, the easiest way to do it is the start shell command. If the thing you start is any command-line program, including python, it will get a new cmd window. So, something like:

subprocess.call('start /wait python bb.py', shell=True)

OS X has a similar command, open. And it's a real program rather than a shell command, so you don't need shell=True. However, running a command-line program or script with open doesn't generally open a new terminal window. In fact, the whole point of it is to allow you to run programs as if they were being double-clicked in Finder, which never runs something in the terminal unless it's a .command file.

So, you can create a temporary .command wrapper file and open that; something like this (untested):

with tempfile.NamedTemporaryFile(suffix='.command') as f:
    f.write('#!/bin/sh\npython bb.py\n')
    subprocess.call(['open', '-W', f.name])

Alternatively, you can explicitly tell open to use Terminal.app, something like this:

subprocess.call(['open', '-W', '-a', 'Terminal.app', 'python', '--args', 'bb.py'])

Or you can script Terminal.app via AppleEvents. For example:

appscript.app('Terminal').do_script('python bb.py')

The "do script" event opens a new window and runs its argument as a command. If you want more detailed control, open the scripting dictionary in AppleScript Editor and see all the fun stuff you can do.


On Linux or other *nix systems… well, there are 65,102 different desktop environments, launchers, and terminal programs. Do you need to work on all of them?

With gnome-terminal, just running the terminal again gives you a new window, and the -x argument lets you specify an initial command, so:

subprocess.call(['gnome-terminal', '-x', 'python bb.py'])

Many older terminals try to be compatible with xterm, which does the same thing with -e, so:

subprocess.call(['xterm', '-e', 'python bb.py'])
subprocess.call(['rxvt', '-e', 'python bb.py'])

… etc.

How do you know which terminal the user is using? Good question. You could walk the like of parent processes from yourself until you find something that looks like a terminal. Or you could just assume everyone has xterm. Or you could look at how various distros configure a default terminal and search for all of them. Or…

2 of 4
19

This should probably be a comment, but since I can't yet...

In Windows , you can do:

subprocess.call('python bb.py', creationflags=subprocess.CREATE_NEW_CONSOLE)
🌐
Educative
educative.io › answers › how-to-run-a-python-script-in-linux
How to run a Python script in Linux
... First, open the terminal, for most Linux flavors using the shortcut "Ctrl + Alt + T" should work but if it doesn't we can type it in the search bar and open the terminal from there.
🌐
Ask Ubuntu
askubuntu.com › questions › 1401619 › how-to-run-python-commands-in-a-new-terminal-window
bash - How to run python commands in a new terminal window - Ask Ubuntu
April 9, 2022 - What you should do is use subprocess.run or similar to run gnome-terminal -x espeak ..., instead of using print() to just show the command you're running.
🌐
GeeksforGeeks
geeksforgeeks.org › python › open-and-run-python-files-in-the-terminal
Open and Run Python Files in the Terminal - GeeksforGeeks
July 23, 2025 - The Linux terminal offers a powerful environment for working with Python files, providing developers with efficient ways to open, edit, and run Python scripts directly from the command line.
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.