Reputation: 10521
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:
doctest
would count, as I can run python -m doctest
foo
would not, as it would return No module named foo
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
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