Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read the first line of the terminal output in Python?

I would like to ask you, how do I check the 1st line of the terminal output for example:
if i do "pip show keyboard" how do i check that it said "WARNING: Package(s) not found: keyboard" in the command prompt?

I have no idea how to do it, the code below is just an example of what I want to do

import os
from time import sleep

keyboard_check = os.system("pip show keyboard")

if keyboard_check[0] == "WARNING: Package(s) not found: keyboard":
    print("keyboard is not installed")
    sleep(1)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Don’t use os.system. It cannot capture stdout/stderr from the child process.

Instead use subprocess.run (or another function in the subprocess package). For example:

keyboard_check = subprocess.run(["pip", "show", "keyboard"], capture_output=True, text=True)
if keyboard_check.stdout.split('\n')[0] == "WARNING: Package(s) not found: keyboard":
    ...

Alternatively, an arguably better way to check for failure is to use the return code of the process. pip show returns 1 if the specified package does not exist. Here’s how that could look:

keyboard_check = subprocess.run(["pip", "show", "--quiet", "keyboard"])
if keyboard_check.returncode != 0:
    ...

This way, you don’t need to depend on the specific error message, so if pip ever changes its warning message you won’t need to come back and update your script.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading