How to Execute a Program or Call a System or Shell Command in Python?

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.

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?