Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 29, 2016 12:00 pm

How to Run Unix Commands in Your Python Program

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:

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:

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:

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:

Let’s see how we can return the date using the subprocess module, but let’s make the example more interesting.

The above example can be run more simply using check_output(), as follows:

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.


Original Link:

Share this article:    Share on Facebook
No Article Link

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code