How to Execute a Program or Call a System or Shell Command in Python?
To execute a program or call a system or shell command in Python, you can use the built-in module called subprocess
. Here's an example:
import subprocess
# Execute a shell command
subprocess.call(["ls", "-l"])
# Execute a program with arguments
subprocess.call(["./my_program", "arg1", "arg2"])
In the first example, we use subprocess.call()
to execute the shell command ls -l
. The shell command is passed as a list of strings, where the first element is the command and the subsequent elements are the arguments.
In the second example, we execute a program called my_program
with two arguments arg1
and arg2
. Note that we need to include the path to the program if it is not in the current directory.
subprocess.call()
returns the return code from the command or program, which can be used to check if the execution was successful.