Skip to content
geeksforgeeks
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Retrieving the output of subprocess.call() in Python
Next article icon

Retrieving the output of subprocess.call() in Python

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The subprocess.call() function in Python is used to run a command described by its arguments. Suppose you need to retrieve the output of the command executed by subprocess.call(). In that case, you'll need to use a different function from the subprocess module, such as subprocess.run(), subprocess.check_output(), or subprocess.Popen().

Introduction to subprocess.call()

The subprocess.call() function is used to execute a shell command. It waits for the command to complete and then returns the command's return code. This function is straightforward when you only need to know whether a command executed successfully or failed (based on the return code). However, it does not directly provide a method to capture the output of the command. For scenarios where capturing the output is necessary, other functions in the subprocess module, such as subprocess.Popen() or subprocess.run(), are more suitable.

Syntax of subprocess.call()

Here is the basic syntax of subprocess.call():

import subprocess
return_code = subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

  • args: This can be a string or a sequence of program arguments. The exact program to execute and its arguments.
  • stdin, stdout, and stderr: These specify the executed program’s standard input, standard output, and standard error file handles, respectively.
  • shell: If shell=True, the specified command will be executed through the shell.

Limitations of subprocess.call()

While subprocess.call() is useful, it has its limitations, particularly:

  • No direct output capture: It does not capture the stdout or stderr of the command. It only returns the exit status of the command.
  • Less control over execution: It provides less control over process execution compared to subprocess.Popen().

Using subprocess.run()

The subprocess.run() function allows you to capture the output by setting the capture_output parameter to True.

Python
import subprocess

result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print("Return code:", result.returncode)
print("Output:", result.stdout)
print("Error:", result.stderr)

Output:

Return code: 0
Output: total 4
drwxr-xr-x 1 root root 4096 Jul 24 13:22 sample_data

Error:

Using subprocess.check_output()

The subprocess.check_output() function runs a command and returns its output as a byte string. You can decode this byte string to get a string.

Python
import subprocess

output = subprocess.check_output(['ls', '-l'], text=True)
print("Output:", output)

Output:

Output: total 4
drwxr-xr-x 1 root root 4096 Jul 24 13:22 sample_data

Using subprocess.Popen()

The subprocess.Popen() function gives you more control over how you interact with the process. You can use it to capture both the standard output and standard error streams.

Python
import subprocess

process = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stdout, stderr = process.communicate()

print("Return code:", process.returncode)
print("Output:", stdout)
print("Error:", stderr)

Output:

Output: total 4
drwxr-xr-x 1 root root 4096 Jul 24 13:22 sample_data

Example Usage

Here are practical examples of how to use subprocess.run(), subprocess.check_output(), and subprocess.Popen() in Python. These examples will demonstrate running a simple shell command and handling its outputs.

1. Example with subprocess.run()

The subprocess.run() function is a versatile tool introduced in Python 3.5 for managing subprocesses. It returns a CompletedProcess instance on completion.

Here’s an example of using subprocess.run() to execute a command and capture its output:

In this example:

  • capture_output=True ensures that the standard output and error are captured.
  • text=True makes the output and error text-based instead of bytes, which is useful for processing in Python.
Python
import subprocess

# Run the 'echo' command and capture its output
result = subprocess.run(["echo", "Hello, World!"], capture_output=True, text=True)

# Accessing the output
print("Output:", result.stdout)
print("Return Code:", result.returncode)

Output:

Output: Hello, World!

Return Code: 0

2. Example with subprocess.check_output()

The subprocess.check_output() function runs a command and returns its output. If the command exits with a non-zero exit code, it raises a subprocess.CalledProcessError.

Here’s how to use subprocess.check_output():

This function:

  • Captures and returns the standard output of the command.
  • Raises an exception if the command fails (non-zero exit status).
Python
import subprocess

try:
    # Run the 'echo' command and capture its output
    output = subprocess.check_output(["echo", "Hello, World!"], text=True)
    print("Output:", output)
except subprocess.CalledProcessError as e:
    print("Failed to run command:", e)

Output:

Output: Hello, World!

3. Example with subprocess.Popen()

The subprocess.Popen() class is used for more complex subprocess management, allowing fine control over I/O streams and the execution environment.

Here’s an example of using subprocess.Popen() to execute a command and capture its output:

In this example:

  • stdout=subprocess.PIPE and stderr=subprocess.PIPE indicate that the standard output and standard error of the command should be captured.
  • process.communicate() waits for the command to complete and returns the output and errors.
  • text=True ensures the outputs are returned as strings.
Python
import subprocess

# Command to execute
command = ["echo", "Hello, World!"]

# Start the subprocess
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

# Wait for the command to complete and get the output
stdout, stderr = process.communicate()

print("Output:", stdout)
print("Errors:", stderr)
print("Return Code:", process.returncode)

Output:

Output: Hello, World!

Errors:
Return Code: 0

Conclusion

To retrieve the output of a command executed by subprocess.call(), you should switch to using subprocess.run(), subprocess.check_output(), or subprocess.Popen(). Each of these functions provides mechanisms to capture and handle the output of the executed command, which subprocess.call() does not offer.


Next Article
Retrieving the output of subprocess.call() in Python

J

joebiiden
Improve
Article Tags :
  • Python
  • python-utility
Practice Tags :
  • python

Similar Reads

    Python | Logging Test Output to a File
    Problem - Writing the results of running unit tests to a file instead of printed to standard output. A very common technique for running unit tests is to include a small code fragment (as shown in the code given below) at the bottom of your testing file. Code #1 : Python3 1== import unittest class M
    2 min read
    Python subprocess module
    The subprocess module present in Python(both 2.x and 3.x) is used to run new applications or programs through Python code by creating new processes. It also helps to obtain the input/output/error pipes as well as the exit codes of various commands. In this tutorial, we’ll delve into how to effective
    9 min read
    Handling Access Denied Error Occurs While Using Subprocess.Run in Python
    In Python, the subprocess module is used to run new applications or programs through Python code by creating new processes. However, encountering an "Access Denied" error while using subprocess.run() can be problematic. This error arises due to insufficient permissions for the user or the Python scr
    5 min read
    Returning a function from a function - Python
    In Python, functions are first-class objects, allowing them to be assigned to variables, passed as arguments and returned from other functions. This enables higher-order functions, closures and dynamic behavior.Example:Pythondef fun1(name): def fun2(): return f"Hello, {name}!" return fun2 # Get the
    5 min read
    How can we display an image in a child process in Python
    Python allows multiprocessing to efficiently utilize multiple CPU cores for concurrent tasks. Displaying an image in a child process involves spawning a separate process using libraries like Tkinter or Matplotlib. This approach makes sure that image loading and display operations can run concurrentl
    2 min read
    Python PRAW - Getting the subreddit on which a comment is posted in Reddit
    In Reddit, we can post a comment to any submission, we can also comment on a comment to create a thread of comments. Here we will see how to fetch the subreddit in which the comment has been posted using PRAW. We will be using the subreddit attribute of the Comment class to fetch subreddit class of
    2 min read
    Multiprocessing in Python | Set 1 (Introduction)
    This article is a brief yet concise introduction to multiprocessing in Python programming language. What is multiprocessing? Multiprocessing refers to the ability of a system to support more than one processor at the same time. Applications in a multiprocessing system are broken to smaller routines
    7 min read
    How to print to stderr and stdout in Python?
    In Python, whenever we use print() the text is written to Python’s sys.stdout, whenever input() is used, it comes from sys.stdin, and whenever exceptions occur it is written to sys.stderr.  We can redirect the output of our code to a file other than stdout. But you may be wondering why one should do
    3 min read
    How to call a function in Python
    Python is an object-oriented language and it uses functions to reduce the repetition of the code. In this article, we will get to know what are parts, How to Create processes, and how to call them.In Python, there is a reserved keyword "def" which we use to define a function in Python, and after "de
    5 min read
    Matplotlib.pyplot.subplot_tool() in Python
    Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. Sample Code Python3 1== # sample code import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4], [16, 4, 1, 8
    1 min read
top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences