0

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)
Shimis
  • 5
  • 4
  • Is [this](https://stackoverflow.com/questions/6466711/what-is-the-return-value-of-os-system-in-python) useful? – Marco Balo Apr 22 '22 at 17:25

1 Answers1

1

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.

0x5453
  • 12,753
  • 1
  • 32
  • 61