[파이썬] subprocess `subprocess.getoutput()`: 명령어 출력 가져오기

In Python, the subprocess module provides a way to run external commands and retrieve their output. One useful function in this module is getoutput(), which allows you to execute a command and capture its output.

Usage

To use subprocess.getoutput(), you first need to import the subprocess module:

import subprocess

Once you have imported the module, you can call the getoutput() function, passing the command you want to execute as a string argument. The function will return the output of the command as a string.

Here’s an example of how to use getoutput():

output = subprocess.getoutput("ls -l")
print(output)

In this example, the ls -l command is executed, and the resulting output is stored in the output variable. The output is then printed to the console.

Important Points to Note

Conclusion

The subprocess.getoutput() function in Python’s subprocess module provides a convenient way to execute external commands and capture their output. By using this function, you can easily integrate command line functionality into your Python applications and process the output as needed. Just remember to handle any potential security risks and validate input before using it in the command.