How do I execute a program or call a system command?

There are several ways to execute a program or call a system command in Python. Here are a few options:

  1. Using the subprocess module:
import subprocess

# To execute a program
subprocess.run(["program_name"])

# To call a system command
subprocess.run(["system_command"])

Watch a course Python - The Practical Guide

  1. Using the os module:
import os

# To execute a program
os.system("program_name")

# To call a system command
os.system("system_command")
  1. Using the Popen() function from the subprocess module:
import subprocess

# To execute a program
process = subprocess.Popen(["program_name"])

# To call a system command
process = subprocess.Popen(["system_command"])

Note: Some system commands may require privileges or may not be available on all systems. Be careful when using system commands as they can potentially be harmful if misused.