Let's study Python

Executing external commands in Python? Here are some methods to help you get the job done efficiently.

# Calling External Commands in Python

When it comes to calling external commands in Python, there are several methods available, each with its own advantages and disadvantages. Let’s explore some of the common ways to execute external commands in Python.

## Using `os.system()`

One of the simplest ways to call external commands in Python is by using the `os.system(…)` function. This function executes the command and returns the exit value of the command. However, the drawback is that it does not capture stdout and stderr.

ret = os.system(‘some_cmd.sh’)
if ret != 0:
print ‘some_cmd.sh execution returned failure’

## Background Execution of External Commands in Python

`subprocess.Popen` provides more flexibility in executing external commands compared to using `os.system`. It allows you to start a command in the background and wait until it completes. You can then retrieve the stdout and stderr.

proc = subprocess.Popen([“./some_cmd.sh”], stdout=subprocess.PIPE)
print ‘waiting for ‘ + str(proc.pid)
print ‘some_cmd.sh execution finished’
(out, err) = proc.communicate()
print ‘some_cmd.sh output : ‘ + out

## Calling Long-Running External Commands in the Background in Python

You can use `subprocess.Popen` to start a long-running process in the background and eventually terminate it when it’s no longer needed.

proc = subprocess.Popen([“./some_long_run_cmd.sh”], stdout=subprocess.PIPE)
# Do something else
# Now some_long_run_cmd.sh execution is no longer needed, so kill it
os.system(‘kill -15 ‘ + str(proc.pid))
print ‘Output : ‘ + proc.communicate()[0]

These are some examples of how you can call external commands in Python using different methods. Each method has its own use cases and benefits, so you can choose the one that best fits your requirements. Remember to handle the output, errors, and return codes appropriately based on your needs.