The os module in Python provides various functions for interacting with the operating system. One very useful function is os.system() which allows us to execute system commands directly from Python code.
In this comprehensive guide, we will cover the ins and outs of using os.system() including:
- What is os.system() and how it works
- The parameters it takes
- The return value
- When to use it and when not to
- Security considerations
- Practical examples such as running system commands, opening applications, getting system info etc.
We will also compare os.system() to other similar functions like os.popen(), subprocess etc. By the end, you‘ll have a deep understanding of integrating system commands in Python using os.system().
What is os.system()?
The os.system() function in Python allows you to execute command line statements directly in Python by passing the statement as a string.
For example:
import os
os.system("date")
Here we are executing the date command.
The key thing is that os.system() takes the command you want to execute as a string parameter. It then runs that command line statement in a subshell.
The main advantage of os.system() is convenience – you can directly execute shell commands without having to deal with any of the lower level details.
Under the hood, os.system() works by passing the system command to the default shell (/bin/sh on Unix/Linux and command.com or cmd.exe on Windows) then getting the output.
This makes it very easy to run external programs that rely on your shell environment including all the PATH variables and aliases you have configured.
Parameters
os.system() takes only one parameter:
- The system command to execute as a string
For example:
os.system("ls -l")
This allows you to pass virtually any command line statement as a string to os.system().
Return value
The return value of os.system() depends on the operating system:
- On Unix/Linux – The return value is the exit code of the process. An exit code of 0 means success. A non-zero exit code means failure.
- On Windows – The return value is the value returned by the command. 0 means success while 1 means failure.
For example:
ret = os.system("ls -l")
print(ret)
# 0
Here ls command executes successfully so os.system() returns 0.
Knowing the return value allows you to programmatically check if a command succeeded or failed.
When to use os.system()
os.system() is best suited for situations where you need to:
- Quickly execute an external system command from Python and don‘t need to process the output or return code
- Run commands that depend on shell features like environment variables, Bash aliases, input/output redirection etc.
- Launch external applications like opening a browser, text editor etc. These types of commands don‘t have any output that needs processing in Python
In essence, os.system() is a great shortcut for running one-off system commands where you don‘t need to parse or process the output in your Python program.
When not to use os.system()
While os.system() offers simplicity and convenience, there are some downsides:
- It is less suited for more complex automation tasks that require executing multiple commands, piping output or checking return codes
- There is no direct access to the output generated by the command. You have to rely on the print statements in your shell to see the output
- It can be slower compared to other options due to the additional overhead of opening and closing a subshell for every function call
In these kinds of situations where you need more control or need to process the command output in Python, it is better to use the subprocess module which allows executing commands from Python without invoking a subshell.
We will do a more detailed comparison between os.system() and subprocess later.
Security Considerations
Since os.system() allows executing arbitrary system commands, you need to be careful with properly sanitizing user input.
If you are taking the command to execute as user input, you must sanitize it to prevent command injection attacks. For example by escaping quotes and other special characters.
Additionally, you may want to maintain a whitelist of allowed commands and block anything not on the list.
Overall be very careful about executing system commands with unvalidated user input.
Practical Examples of Using os.system()
Now that we have covered the basics of os.system(), let‘s look at some practical examples of how to use it for integrating system commands in Python.
1. Getting Date and Time
We can use the date command to quickly get current date and time:
import os
os.system("date")
Output:
Sat Feb 11 03:28:29 PM EST 2023
Similarly, we can execute the cal command to print the calendar:
os.system("cal")
Output:
February 2023
Su Mo Tu We Th Fr Sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28
2. Listing Files and Directories
We can execute the ls command to list files and directories:
os.system("ls -l ~/Documents")
This will do a long listing of all files and folders under the Documents directory.
3. Opening Applications
os.system() is very handy for launching graphical applications like web browser, text editor etc.:
os.system("gedit test.txt")
This will open the test.txt file in the gedit text editor.
We can also open Firefox browser:
os.system("firefox www.google.com")
And so on…
4. Reading System Info
We can use commands like uname and lsb_release to quickly get system information:
os.system("uname -a")
os.system("lsb_release -a")
This prints kernel version and Linux distribution information respectively.
5. Running Linux Commands
We can execute other common Linux commands like ping, df, kill etc.:
os.system("ping -c 5 google.com")
os.system("df -h")
os.system("kill 1234")
And really any other command you would normally run on your terminal.
Comparison Between os.system() vs subprocess
The subprocess module provides a more advanced way to execute external system commands from Python. Key differences are:
- os.system() runs the command in a subshell which adds overhead
- subprocess runs the command directly without invoking a shell
- os.system() does not capture output generated by the command
- subprocess allows getting output and return codes for processing
- subprocess allows piping output from one command to another
In summary, subprocess gives you more flexibility and control compared to os.system().
But os.system() is simpler and more convenient for one-off commands where you don‘t need to process the output.
os.system() vs os.popen()
Python also provides the os.popen() method which can be used similarly to os.system() for running system commands.
Key differences are:
- os.popen() opens a pipe to the command which can be used to read output
- os.system() does not provide direct access to output
- os.popen() is better suited for getting a command‘s output
- os.system() is better for just running a command quickly
In essence, os.popen() allows getting the command output for processing while os.system() just executes the command.
Conclusion
os.system() in Python offers a simple and convenient way to directly run system commands and shell statements by passing them as a string parameter.
It saves you from having to deal with all the low level details when you just want to quickly execute an external program or system call from Python.
However, it does come with limitations around getting output or exit codes back from the executed command.
For more complex command execution and processing of outputs, the subprocess module is better equipped.
Overall, os.system() strikes the right balance between simplicity and capability to integrate external commands direclty from your Python code. Used properly, it can simplify writing many automations, tools or system administration tasks in Python.


