[파이썬] subprocess `subprocess.pwd`: 작업 디렉터리 설정

In Python, the subprocess module provides a way to interact with the system and execute external commands. One useful aspect of this module is the ability to change or set the working directory for the executed command.

The subprocess module has a built-in function called os.getcwd() to retrieve the current working directory. However, to change the working directory, we often use the os.chdir(path) function. But in some cases where we need to execute an external command in a different working directory, we can utilize the subprocess module itself.

Let’s take a look at how to set the working directory using the subprocess module in Python.

Using the subprocess Module to Set the Working Directory

To set the working directory using the subprocess module, we can make use of the cwd parameter in the subprocess.run() function. This parameter allows us to specify the working directory for the command being executed.

Here’s an example that demonstrates how to set the working directory using subprocess:

import subprocess

path_to_directory = "/path/to/directory"
command_to_execute = "ls"

subprocess.run(command_to_execute, cwd=path_to_directory, shell=True)

In the above example, we have path_to_directory variable that stores the desired working directory path. We also have command_to_execute variable that contains the external command we want to run. The subprocess.run() function is then called with the cwd parameter set to path_to_directory.

The cwd parameter in subprocess.run() specifies the working directory for the command to be executed. By setting this parameter, the external command will be executed within the specified directory.

Why Use subprocess to Set the Working Directory?

You might be wondering why you should use the subprocess module to set the working directory instead of using the os.chdir() function. Well, the primary reason is that by using subprocess, you can set the working directory specifically for the external command being executed, without affecting the working directory of the current Python process.

This can be incredibly useful in scenarios where you want to execute multiple commands in different directories within a single Python script. It allows you to isolate the effect of each command on its respective working directory.

Conclusion

Setting the working directory for executed commands is essential in certain situations. The subprocess module in Python provides a convenient way to achieve this by using the cwd parameter in the subprocess.run() function.

By understanding how to manipulate the working directory using subprocess, you can enhance the flexibility and functionality of your Python scripts when it comes to executing external commands.