[파이썬] subprocess 다른 Python 스크립트 실행하기

Python’s subprocess module provides a way to execute external commands and programs from within Python. This can be useful when you want to run another Python script from an existing Python script. In this blog post, we will explore how to use subprocess to execute a different Python script.

Using subprocess.run()

subprocess.run() is a convenient function that allows us to execute an external command or program. To run a different Python script, we can pass the path to the script as an argument.

import subprocess

# Path to the other Python script
other_script = 'path/to/other_script.py'

# Execute the other script
subprocess.run(['python', other_script])

In the above example, we import the subprocess module and specify the path to the other Python script we want to execute. We then use subprocess.run() to run the script by passing ['python', other_script] as the command to execute.

Passing Arguments to the Other Script

We can also pass arguments to the other Python script by including them as additional elements in the command list.

import subprocess

# Path to the other Python script
other_script = 'path/to/other_script.py'

# Arguments to pass to the script
arguments = ['--arg1', 'value1', '--arg2', 'value2']

# Execute the other script with arguments
subprocess.run(['python', other_script] + arguments)

In the above example, we define a list called arguments, which contains the arguments to be passed to the other script. We then concatenate this list with the command list in subprocess.run() using the + operator.

Handling the Output

By default, subprocess.run() captures the output of the command and returns a CompletedProcess object. We can access the output using the stdout attribute.

import subprocess

# Path to the other Python script
other_script = 'path/to/other_script.py'

# Execute the other script and capture the output
result = subprocess.run(['python', other_script], capture_output=True)

# Print the output
print(result.stdout)

In the above example, we set capture_output=True to capture the output from the other script. We then access the output using the stdout attribute of the result object.

Conclusion

In this blog post, we explored how to use subprocess to execute a different Python script from within another Python script. We learned how to pass arguments to the other script and capture the output. This functionality can be helpful in automating tasks or running external scripts as part of a larger Python project.