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.
os.system()
One solution to this issue is to use os.system()
from Python’s os
module.
As mentioned in the documentation, os.system()
:
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.
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:
Tue May 24 17:29:20 CEST 2016
call()
Although os.system()
works, it is not recommended as it is considered a bit old and deprecated. A more recommended solution is Python’s subprocess
module call(args)
function. 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 'It is', output
The above example can be run more simply using check_output()
, as follows:
import subprocess time = subprocess.check_output('date') print 'It is', time
The output of the above scripts is:
It is Tue May 24 19:14:22 CEST 2016
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.
Conclusion
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 from the Python documentation.
No comments:
Post a Comment