在 Python 中识别可执行文件的最佳方法是什么?
我发现以下函数会找到记事本可执行文件
from shutil import which
which('notepad')
Out[32]: 'C:\\Windows\\system32\\notepad.EXE'
另一种方法。
from distutils import spawn
spawn.find_executable('notepad')
Out[38]: 'C:\\Windows\\system32\\notepad.exe'
虽然这两种方法都适用于记事本,但我似乎无法让它们找到其他可执行文件,例如 vlc.exe、gimp-2.10.exe 或其他文件。在计算机上查找可执行文件的更好方法是什么?
最佳答案
这是独立于平台的有效方法:
import subprocess
import os
import platform
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
def find_prog(prog):
if is_tool(prog):
cmd = "where" if platform.system() == "Windows" else "which"
return subprocess.call([cmd, prog])
关于python - 如何在Python中找到可执行文件的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55394905/