我有一個(gè)接受命令的函數(shù):import subprocessdef run_command(command: str): subprocess.run(['python', '-m', command])我想告訴您是否command可以作為python -m <command>.例如:doctest會(huì)算,因?yàn)槲铱梢耘躳ython -m doctestfoo不會(huì),因?yàn)樗鼤?huì)返回No module named foo有沒有辦法告訴我,在我的函數(shù)中,是否command有一個(gè)可以運(yùn)行的 Python 模塊?最簡(jiǎn)單的方法就是try-except,但我想避免這樣做,因?yàn)樗赡軙?huì)掩蓋其他錯(cuò)誤。
1 回答

翻閱古今
TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以捕獲命令的輸出并檢查 stderr 以查看它返回的內(nèi)容。此代碼檢查二進(jìn)制字符串“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
添加回答
舉報(bào)
0/150
提交
取消