728x90
Here is a basic example of how to use the subprocess module to run an external command
Using subprocess.run
The subprocess.run function is the recommended approach for most cases because it is simple and powerful.
import subprocess
# Command to be executed
command = ["ls", "-l"] # Replace with your command and arguments
# Run the command
result = subprocess.run(command, capture_output=True, text=True)
# Output the result
print("Return code:", result.returncode)
print("Output:", result.stdout)
print("Error:", result.stderr)
- Replace ["ls", "-l"] with the command you want to run. If your command is a string, split it into a list of arguments.
- Use capture_output=True and text=True in subprocess.run to capture and return the output as a string.
Using subprocess.Popen
For more advanced use cases where you need more control over the input/output pipes, you can use subprocess.Popen.
import subprocess
# Command to be executed
command = ["ls", "-l"] # Replace with your command and arguments
# Run the command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
# Get the output and error messages
stdout, stderr = process.communicate()
# Output the result
print("Return code:", process.returncode)
print("Output:", stdout)
print("Error:", stderr)
- When using subprocess.Popen, use stdout=subprocess.PIPE and stderr=subprocess.PIPE to capture the output and error messages.
Using os.system
The os.system function can also be used to run shell commands. However, it is less flexible and does not provide as much control over the input/output/error pipes as the subprocess module.
import os
# Command to be executed
command = "ls -l" # Replace with your command
# Run the command
exit_code = os.system(command)
# Output the result
print("Return code:", exit_code)
References
* subprocess — Subprocess management — Python 3.12.4 documentation
728x90
'Data Science > Python' 카테고리의 다른 글
[Python] 대용량 데이터 처리 및 분석을 위한 Duck DB (3) | 2024.10.12 |
---|---|
Pandas의 한계를 극복한 5가지 라이브러리: Dask, Vaex, Modin, Cudf, Polars (0) | 2023.09.21 |
[Image Analysis] Completely Black or White Image Detection (0) | 2023.07.27 |
[Python] Transfer Pandas Dataframe to MYSQL database with SSH (0) | 2023.02.22 |
[python] Chrome web-driver options : speed up page loading. (0) | 2023.01.31 |
최근댓글