The subprocess module is a very good solution.

import subprocess
p = subprocess.Popen([command, argument1,...], cwd=working_directory)
p.wait()

It has also arguments for modifying environment variables, redirecting input/output to the calling program, etc.

Answer from hynekcer on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › running a shell command from python to execute a file in different directory
r/learnpython on Reddit: running a shell command from python to execute a file in different directory
November 22, 2021 -

Can't tell where I messed this up... I am using pycharm and the folder with all of the files on it is on my desktop....

os.system("cd C:\\softwares\\someDirectory\\subdirectory\\bin execute.sql")

Am I doing this correctly? If I open up the command prompt and just cd to the directory and run the command it runs... but when I try to CD and run it from my python script it spits out the following error

The system cannot find the path specified.

thoughts?

🌐
Python
docs.python.org › 3 › library › subprocess.html
subprocess — Subprocess management
2 weeks ago - Changed in version 3.8: executable ... for shell=True. The current directory and %PATH% are replaced with %COMSPEC% and %SystemRoot%\System32\cmd.exe....
Discussions

Python: run shell command in a specific directory - Stack Overflow
I can't define the directory of my maven project and maven tries to compile in directory of Python script. Is there any standard way to define execution directory for the shell command? More on stackoverflow.com
🌐 stackoverflow.com
python - How to change the working directory for a shell script - Unix & Linux Stack Exchange
I'm setting it up in webmin, and I believe its creating a shell script to call it. Through the startup script, I'm doing something like this to call the script: execute python home/username/projectname/scriptname.py · The script is starting up fine, but it can't access the files in the relative directory... More on unix.stackexchange.com
🌐 unix.stackexchange.com
July 8, 2012
Execute shell commands in Python - Unix & Linux Stack Exchange
I'm currently studying penetration testing and Python programming. I just want to know how I would go about executing a Linux command in Python. The commands I want to execute are: echo 1 > /pr... More on unix.stackexchange.com
🌐 unix.stackexchange.com
Can I do a "dir" (OS command) from within the Python shell?
System: Python 3.9 (for the purpose of a tutorial I’m still doing) on Windows 10. I did some searching and have not found an answer yet. While in the python shell sometimes I want to see a list of files and do “dir” or “dir /o-d” or “dir” with some other switches. More on discuss.python.org
🌐 discuss.python.org
4
0
March 11, 2024
🌐
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. You’ll see the content of the current working directory ...
🌐
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.
🌐
Stack Abuse
stackabuse.com › executing-shell-commands-with-python
Executing Shell Commands with Python
January 6, 2023 - In this script, we create two variables that store the result of executing commands that change the directory to the home folder, and to a folder that does not exist. Running this file, we will see: $ python3 cd_return_codes.py `cd ~` ran with exit code 0 sh: line 0: cd: doesnotexist: No such file or directory `cd doesnotexist` ran with exit code 256
Find elsewhere
🌐
Python
docs.python.org › 3 › using › cmdline.html
1. Command line and environment — Python 3.14.4 documentation
When called with a directory name argument, it reads and executes an appropriately named script from that directory. When called with -c command, it executes the Python statement(s) given as command.
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.

🌐
Martin Heinz
martinheinz.dev › blog › 98
The Right Way to Run Shell Commands From Python | Martin Heinz | Personal Website & Blog
June 5, 2023 - When we invoke sh.some_command, sh library tries to look for builtin shell command or a binary in your $PATH with that name. If it finds such command, it will simply execute it for you. If the command is not in $PATH, then you can create instance of Command and call it that way.
🌐
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.
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.

🌐
GoLinuxCloud
golinuxcloud.com › home › programming › how to run shell commands in python? [solved]
How to run shell commands in Python? [SOLVED] | GoLinuxCloud
January 9, 2024 - Here is an example of using sh to run a shell command inside Python: ... In this example, we use the ls command from the sh library to run the command ls -l. The output of the command is captured in the output variable, which is an instance of the sh’s RunningCommand class. This class has a stdout attribute that contains the output of the command as a string. If you get ModuleNotFoundError: No module named 'sh' while executing this program then you can manually install this module using pip:
🌐
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.
🌐
iO Flood
ioflood.com › blog › python-run-shell-command
Using Python to Run Shell Commands
December 7, 2023 - In this script, we’re using the subprocess.run() function to create a new directory and list its contents. This is a simple example, but the same principles can be applied to automate more complex tasks. System administrators often use Python to manage system resources. For instance, they might use it to monitor system performance, manage files, or automate software installation. Python’s ability to run shell commands makes it a powerful tool for these tasks.
🌐
Python Data Science Handbook
jakevdp.github.io › PythonDataScienceHandbook › 01.05-ipython-and-shell-commands.html
IPython and Shell Commands | Python Data Science Handbook
As an example, here is a sample of a Linux/OSX shell session where a user explores, creates, and modifies directories and files on their system (osx:~ $ is the prompt, and everything after the $ sign is the typed command; text that is preceded by a # is meant just as description, rather than something you would actually type in): osx:~ $ echo "hello world" # echo is like Python's print function hello world osx:~ $ pwd # pwd = print working directory /home/jake # this is the "path" that we're sitting in osx:~ $ ls # ls = list working directory contents notebooks projects osx:~ $ cd projects/ # cd = change directory osx:projects $ pwd /home/jake/projects osx:projects $ ls datasci_book mpld3 myproject.txt osx:projects $ mkdir myproject # mkdir = make new directory osx:projects $ cd myproject/ osx:myproject $ mv ../myproject.txt ./ # mv = move file.
🌐
OneUptime
oneuptime.com › home › blog › how to execute system commands from python
How to Execute System Commands from Python
January 25, 2026 - import subprocess # Command as a list (recommended) # Each element is a separate argument - safer and clearer result = subprocess.run( ['git', 'status', '--short'], # Command and arguments as list capture_output=True, # Capture stdout and stderr text=True, # Return strings instead of bytes cwd='/path/to/repo', # Working directory timeout=30, # Kill after 30 seconds check=True, # Raise exception on non-zero exit ) import subprocess result = subprocess.run( ['python', '--version'], capture_output=True, text=True ) print(f"stdout: {result.stdout}") print(f"stderr: {result.stderr}")