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
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기
반응형