How to execute a program or call a system command in Python?

0
0

ython provides several ways to execute programs or call system commands, some of which are:

  1. Using the os module: You can use the os module to execute a program or call a system command. Here’s an example:

import os
os.system(“ls”)

 

This will execute the ls command in the terminal.

  1. Using the subprocess module: The subprocess module provides a more powerful way to execute programs or call system commands. Here’s an example:

import subprocess
result = subprocess.run([“ls”, “-l”], stdout=subprocess.PIPE)
print(result.stdout.decode())

This will execute the ls -l command and capture its output to a variable called result. Then it will print the output to the console.

  1. Using the os.system() method: You can use the os.system() method to execute a system command. Here’s an example:

import os
os.system(“echo Hello World!”)

This will execute the echo Hello World! command in the terminal.

  1. Using the os.popen() method: You can use the os.popen() method to execute a system command and capture its output. Here’s an example:

import os
output = os.popen(“ls”).read()
print(output)

This will execute the ls command and capture its output to a variable called output. Then it will print the output to the console.

  • You must to post comments
Showing 0 results
Your Answer

Please first to submit.