从python脚本检查程序是否存在 [英] Check if a program exists from a python script

查看:64
本文介绍了从python脚本检查程序是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 python 脚本检查程序是否存在?

How do I check if a program exists from a python script?

假设您想检查 wgetcurl 是否可用.我们假设它们应该在路径中.

Let's say you want to check if wget or curl are available. We'll assume that they should be in path.

最好能看到多平台解决方案,但目前,Linux 就足够了.

It would be the best to see a multiplatform solution but for the moment, Linux is enough.

提示:

  • 运行命令并检查返回代码并不总是足够的,因为即使您尝试 --version,某些工具也会返回非 0 结果.
  • 检查命令时,屏幕上不应显示任何内容
  • running the command and checking for return code is not always enough as some tools do return non 0 result even when you try --version.
  • nothing should be visible on screen when checking for the command

另外,我希望有一个更通用的解决方案,例如 is_tool(name)

Also, I would appreciate a solution that that is more general, like is_tool(name)

推荐答案

import subprocess
import os

def is_tool(name):
    try:
        devnull = open(os.devnull)
        subprocess.Popen([name], stdout=devnull, stderr=devnull).communicate()
    except OSError as e:
        if e.errno == os.errno.ENOENT:
            return False
    return True

这篇关于从python脚本检查程序是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆