Home >Backend Development >Python Tutorial >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:
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!