Questions &
Answers with MarsDevs


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


You can perform a function of the program/call a system command via Python’s subprocess module.

It offers a convenient way to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

Here’s an example -

import subprocess

#Replace "your_command_here" with the actual command you want to execute
command  = "your_command_here"

#Run the command 
   result = subprocess.run(command, shell=True, check=True, text=True)
   print("Command output:", result.stdout)
except subprocess.CalledProcessError as e:
   print("Command failed with error:", e)

However, if you are working with user inputs, consider using the shlex.quote() function to properly escape and quote the arguments.

import shlex 
import subprocess

user_input = "user_input_here"
command = f"your_command_here {shlex.quote(user_input)}"

#Rest of the code remains the same 

Also, if you want to execute a child program in a new process, use the subprocess.Popen().

import subprocess
subprocess.Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])