ignoring_gravity
ignoring_gravity

Reputation: 10521

Programmatically detect whether command can be run as module

I have a function which takes a command:

import subprocess


def run_command(command: str):
    subprocess.run(['python', '-m', command])

I would like to tell whether command is something which can be run as python -m <command>.

For example:

Is there a way to tell, inside my function, whether command is a Python module which can be run?

The simplest way would just be try-except, but I would like to avoid that as it might mask other errors.

Upvotes: 0

Views: 58

Answers (1)

incarnadine
incarnadine

Reputation: 700

You can capture the output of the command and check stderr to see what it returned. This code checks if the binary string "No module named" is in the stderr, which means the command wasn't found

import subprocess


def run_command(command: str):
    output = subprocess.run(['python', '-m', command], capture_output=True)
    if b"No module named" in output.stderr:
      print("Command not found")
    else:
      #command was found

Upvotes: 2

Related Questions