测试Python中是否存在可执行文件? [英] Test if executable exists in Python?
问题描述
在Python中,有没有一种可移植且简单的方法来测试可执行程序是否存在?
In Python, is there a portable and simple way to test if an executable program exists?
简单来说,我的意思是像which
命令那样的东西,非常完美.我不想手动搜索PATH或涉及尝试使用Popen
& al,看看它是否失败(这就是我现在正在做的,但是可以想象它是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哪个"命令的行为.
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屋!