[파이썬] subprocess `subprocess.shell=True`: 쉘에서 명령 실행

In Python, the subprocess module provides the ability to run shell commands from within a Python script. Whether you need to execute a single command or a series of commands, the subprocess module has you covered.

Note: The use of the subprocess module to run shell commands can be a potential security risk. Make sure to validate and sanitize any user input before executing shell commands.

Running a Single Shell Command

To run a single shell command using subprocess, you can use the run() function. Here’s an example:

import subprocess

command = "ls -l"
result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True)

print(result.stdout)

In this example, the ls -l command is executed using the subprocess.run() function. The shell parameter is set to True to indicate that the command should be executed using the shell. The check parameter is set to True to raise an exception if the command fails. The capture_output parameter is set to True to capture the output of the command, and the text parameter is set to True to ensure the output is returned as a string.

Running Multiple Shell Commands

If you need to run multiple shell commands, you can use the Popen class from subprocess. Here’s an example:

import subprocess

commands = [
    "echo 'Hello, World!'",
    "ls -l",
    "uname -a"
]

for command in commands:
    process = subprocess.Popen(command, shell=True)
    process.wait()

In this example, a list of commands is defined, and a loop is used to iterate over the commands. For each command, a new instance of subprocess.Popen is created, and the shell parameter is set to True. The wait() method is then called to block until the command finishes executing.

Conclusion

The subprocess module in Python provides a convenient way to execute shell commands from within your Python scripts. Whether you need to run a single command or a series of commands, subprocess has the flexibility to meet your needs. Just make sure to handle user input carefully to avoid any potential security risks.

Remember to experiment and explore the subprocess module further to discover additional features and options that can enhance your shell command execution capabilities in Python.