What are the ways to call external programs in Python


There are several ways to call external programs using Python code. Here are a few examples:


The subprocess module: This module provides a way to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. It is a powerful and flexible way to call external programs from Python. Here’s an example:

import subprocess

# Call an external program and capture its output
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)

# Print the output
print(result.stdout.decode())

In this example, the subprocess.run() function is used to call the ls command with the -l option, which lists the contents of the current directory in a long format. The stdout argument is set to subprocess.PIPE, which captures the output of the command. The output is then printed to the console using print().


The os module:
This module provides a way to interact with the operating system, including running external programs. Here’s an example:

import os

# Call an external program
os.system('ls -l')

In this example, the os.system() function is used to call the ls command with the -l option. The output is printed directly to the console.


The sh module: This module provides a way to run shell commands from Python. Here’s an example:

import sh

# Call an external program
result = sh.ls('-l')

# Print the output
print(result)

In this example, the sh.ls() function is used to call the ls command with the -l option. The output is captured in a variable and then printed to the console using print(). Note that the sh module requires that the external program be installed on the system and accessible from the shell.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *