[파이썬] subprocess `subprocess.getstatus()`: 프로세스 상태 코드 가져오기 (deprecated)

When working with subprocesses in Python, it’s important to be able to retrieve the status code of a process after it has completed. The subprocess module provides a handy function called getstatus() that can be used for this purpose. However, please note that this function is deprecated since Python 3.5 and has been replaced by the subprocess.run() function.

Why is subprocess.getstatus() deprecated?

The getstatus() function was deprecated in favor of the more versatile and comprehensive subprocess.run() function, which was introduced in Python 3.5. The run() function provides a simplified interface for running subprocesses and captures the process’ return code automatically.

How to use subprocess.getstatus()?

To use subprocess.getstatus(), you first need to import the subprocess module in your Python script:

import subprocess

Then, you can use the getstatus() function to run a command and get the status code:

status, output = subprocess.getstatusoutput("<your command>")

Here, status will contain the return code of the command, and output will contain the captured output of the command.

Example usage

Let’s say we want to run a simple command like ls -l and get its status code using the getstatus() function:

import subprocess

status, output = subprocess.getstatusoutput("ls -l")

if status == 0:
    print("Command executed successfully!")
else:
    print("Command failed with status code:", status)

In the example above, if the ls -l command is executed successfully, the script will print “Command executed successfully!”. Otherwise, it will print “Command failed with status code:” along with the actual status code.

Conclusion

Although subprocess.getstatus() is a convenient function for getting the status code of a process, it has been deprecated since Python 3.5 in favor of the more powerful subprocess.run() function. It is recommended to update your code to use the new function to ensure compatibility and take advantage of the enhanced features it provides.