以编程方式检测命令是否可以 运行 作为模块

Programmatically detect whether command can be run as module

我有一个接受命令的函数:

import subprocess


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

我想知道 command 是否可以 运行 为 python -m <command>

例如:

有没有办法在我的函数中判断 command 是否是一个 Python 模块,它可以是 运行?

最简单的方法就是 try-except,但我想避免这样做,因为它可能会掩盖其他错误。

您可以捕获命令的输出并检查 stderr 以查看返回的内容。此代码检查二进制字符串“No module named”是否在 stderr 中,这意味着未找到该命令

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