测试 Python 中是否存在可执行文件? [英] Test if executable exists in Python?

查看:22
本文介绍了测试 Python 中是否存在可执行文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,是否有一种可移植且简单的方法来测试可执行程序是否存在?

In Python, is there a portable and simple way to test if an executable program exists?

简单来说,我的意思是类似于 which 命令,它会是完美的.我不想手动搜索 PATH 或涉及尝试使用 Popen & 执行它的事情.看看它是否失败(这就是我现在正在做的,但想象一下它是 launchmissiles)

By simple I mean something like the which command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with Popen & al and see if it fails (that's what I'm doing now, but imagine it's launchmissiles)

推荐答案

我能想到的最简单的方法:

Easiest way I can think of:

def which(program):
    import os
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None

编辑:更新了代码示例以包含用于处理所提供参数已经是可执行文件的完整路径(即which/bin/ls")的情况的逻辑.这模仿了 UNIX 'which' 命令的行为.

Edit: Updated code sample to include logic for handling case where provided argument is already a full path to the executable, i.e. "which /bin/ls". This mimics the behavior of the UNIX 'which' command.

编辑:更新为使用 os.path.isfile() 而不是 os.path.exists() 每条评论.

Edit: Updated to use os.path.isfile() instead of os.path.exists() per comments.

编辑:path.strip('"') 在这里似乎是错误的做法.Windows 和 POSIX 似乎都不鼓励引用 PATH 项.

Edit: path.strip('"') seems like the wrong thing to do here. Neither Windows nor POSIX appear to encourage quoted PATH items.

这篇关于测试 Python 中是否存在可执行文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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