pro*_*eek 64 python command which
我需要通过运行which abc
命令来设置环境.是否有Python等效的which
命令功能?这是我的代码.
cmd = ["which","abc"]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
res = p.stdout.readlines()
if len(res) == 0: return False
return True
Run Code Online (Sandbox Code Playgroud)
Raf*_*ter 87
有distutils.spawn.find_executable()
Python 2.4+
iLo*_*Tux 54
我知道这是一个较旧的问题,但如果您碰巧使用的是Python 3.3+,则可以使用shutil.which(cmd)
.你可以在这里找到文档.它具有在标准库中的优势.
一个例子是这样的:
>>> import shutil
>>> shutil.which("bash")
'/usr/bin/bash'
Run Code Online (Sandbox Code Playgroud)
Gon*_*lde 13
没有命令可以做到这一点,但你可以迭代environ["PATH"]
并查看文件是否存在,这实际上是什么which
.
import os
def which(file):
for path in os.environ["PATH"].split(os.pathsep):
if os.path.exists(os.path.join(path, file)):
return os.path.join(path, file)
return None
Run Code Online (Sandbox Code Playgroud)
祝好运!