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

Time:04-23

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)

CodePudding user response:

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.

  • Related