Unix is an operating system which was developed in around 1969 at AT&T Bell Labs by Ken Thompson and Dennis Ritchie. There are many interesting Unix commands we can use to carry out different tasks. The question is, can we use such commands directly within a Python program? This is what I will show you in this tutorial.
The Unix command
ls lists all files in the directory. If you put
ls as is in a Python script, this is what you will get when you run the program:
Traceback (most recent call last): File "test.py", line 1, in <module> ls NameError: name 'ls' is not defined
This shows that the Python interpreter is treating
ls as a variable and requires it to be defined (i.e. initialized), and did not treat it as a Unix command.
One solution to this issue is to use
os.system() from Python’s os module.
As mentioned in the documentation,
Executes the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations.
So we can run the
ls command in Python as follows:
import os os.system('ls')
This will return the list of files in your current directory, which is where your
.py program is located. My current directory looks like this:
env unixfile.py workwithexcel
Let’s take another example. If you want to return the current date and time, you can use the Unix command
date as follows:
import os os.system('date')
In my case, this was what I got as a result of the above script:
Thu 24 Apr 2022 10:42:41 AM EAT
os.system() works, it is not recommended as it is considered a bit old and deprecated. A better solution is the
call(args) function from Python’s subprocess module. As mentioned in the documentation about this function:
Run the command described by args. Wait for command to complete, then return the returncode attribute.
If we want to run the
ls Unix command using this method, we can do the following:
from subprocess import call call('ls')
Let’s see how we can return the date using the
subprocess module, but let’s make the example more interesting.
import subprocess time = subprocess.Popen('date', stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = time.communicate() print('Todays date is ', output)
The above example can be run more simply using
check_output(), as follows:
import subprocess time = subprocess.check_output('date') print('Todays date is', time)
The output of the above script is:
Todays date is b'Thu 24 Apr 2022 10:48:19 AM EAT\n'
The above examples show the flexibility in using different
subprocess functions, and how we can pass the results to variables in order to carry out further operations.
As we saw in this tutorial, Unix commands can be called and executed using the
subprocess module, which provides much flexibility when working with Unix commands through its different functions. You can learn more about this module and its different functions in the Python documentation.