Home >Backend Development >Python Tutorial >How Can I Retrieve Output from subprocess.call()?

How Can I Retrieve Output from subprocess.call()?

Linda Hamilton
Linda HamiltonOriginal
2024-12-05 03:53:09482browse

How Can I Retrieve Output from subprocess.call()?

Retrieving Output from Subprocesses Using Subprocess.call()

To retrieve the output from a subprocess launched using subprocess.call(), you can leverage the capabilities of the subprocess module. Here's how:

For Python Version 2.7 and Later:

Utilize subprocess.check_output():

import subprocess

output = subprocess.check_output(["ping", "-c", "1", "8.8.8.8"])

This approach returns the standard output as a string, effectively handling the output retrieval task.

For Python Versions Prior to 2.7:

You can redirect the output using the shell:

import subprocess

process = subprocess.Popen(["ping", "-c", "1", "8.8.8.8"], shell=True, stdout=subprocess.PIPE)

# Read the output
output = process.communicate()[0]

Additional Notes:

  • This method is suitable for simple commands.
  • When using subprocess.Popen(), ensure the stdout parameter is set to subprocess.PIPE to retrieve the output.
  • If the command utilizes Linux syntax, remember to adjust it accordingly for Windows.

For further details and alternative approaches, refer to the comprehensive explanation provided in this other answer.

The above is the detailed content of How Can I Retrieve Output from subprocess.call()?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn