2012-03-26 95 views
11

换言之,是否有跨平台的方式知道subprocess.Popen(file)将在不首先执行的情况下执行哪个文件?是否有与'which'命令相当的Python

+2

https://github.com/amoffat/pbs/blob/master/pbs.py#L95 – 2012-03-26 18:21:17

+0

默认情况下,子inherents父进程的环境。因此,对于PATH中的任何可执行文件(或相应的操作系统),不需要指定位置。 – 2012-03-26 20:12:01

+0

@JoshLee看起来像PBS不再可用。 – Joe 2013-06-03 19:16:53

回答

8

我相信是有没有在Python库

>>> def which(pgm): 
    path=os.getenv('PATH') 
    for p in path.split(os.path.pathsep): 
     p=os.path.join(p,pgm) 
     if os.path.exists(p) and os.access(p,os.X_OK): 
      return p 


>>> os.which=which 
>>> os.which('ls.exe') 
'C:\\GNUwin32\\bin\\ls.exe' 
24

的Python 3.3添加shutil.which()提供发现可执行文件的跨平台方式:

http://docs.python.org/3.3/library/shutil.html#shutil.which

返回路径一个可执行文件,如果给定的cmd被调用就会运行。如果不会调用cmd,则返回None。

样来电:

>>> shutil.which("python") 
'/usr/local/bin/python' 

>>> shutil.which("python") 
'C:\\Python33\\python.EXE' 

不幸的是,这并没有被移植到2.7.x.

+2

版本3.3的shutil.shich实现的Python源代码在这里(只有几十行):http:// hg如果你将第1110行更改为'if if([cmd.lower()。endswith(ext.lower())for ext in pathext]).python.org/cpython/file/6860263c05b3/Lib/shutil.py#l1068 – joemaller 2013-06-10 13:53:56

+1

) '(将发生器转换为列表)比在python 2.7中可用。 – cdhagmann 2014-04-11 13:01:00

+2

Backport可在这里找到:https://github.com/mbr/shutilwhich – 2016-02-13 15:20:15

7

为Python 2和3的选项:

from distutils.spawn import find_executable 

find_executable('python') # '/usr/bin/python' 

find_executable('does_not_exist') # None 

find_executable(executable, path=None)只是试图找到在 '路径' 中列出的目录 '可执行文件'。如果'路径'是None,则默认为os.environ['PATH']。如果未找到,则返回“可执行”或None的完整路径。

请记住,与which不同,find_executable实际上并未检查结果是否标记为可执行文件。如果您想确定subprocess.Popen将能够执行文件,您可能需要致电os.access(path, os.X_OK)来自行检查。


另外值得注意的是,Python的3.3+的shutil.which已经通过第三方模块whichcraft被移植,并为Python 2.6,2.7提供,和3.x。

它可以通过上述GitHub页面(即pip install git+https://github.com/pydanny/whichcraft.git)或Python包索引(即pip install whichcraft)进行安装。它可用于像这样的:

from whichcraft import which 

which('wget') # '/usr/bin/wget' 
相关问题