2012-01-21 53 views
6

如何在linux中使用python搜索可執行文件?可執行文件沒有擴展名,並且與具有不同擴展名的文件一起位於文件夾中。謝謝如何在Linux中使用python搜索可執行文件?

編輯:我的意思是搜索是獲取所有可執行文件的文件名並將它們存儲在列表或元組中。謝謝

+1

http://superuser.com/questions/38981/how-to-find-the-executable-files-under-a-certain-directory-in-linux完全重複 –

+2

不準確的複製。這一個是關於python –

+0

使用'subprocess.popen()'與上述鏈接中提到的命令。 – RanRag

回答

6

Python中做到這一點:

import os 
import stat 

executable = stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH 
for filename in os.listdir('.'): 
    if os.path.isfile(filename): 
     st = os.stat(filename) 
     mode = st.st_mode 
     if mode & executable: 
      print(filename,oct(mode)) 
1

如果通過搜索,您的意思是列出目錄中的所有可執行文件,而不是使用此SuperUser Link中的命令。您可以使用Subprocess module從python代碼執行命令。

import shlex 
executables = shlex.split(r'find /dir/mydir -executable -type f') 
output_process = subprocess.Popen(executables,shell=True,stdout=subprocess.PIPE) 
1

功能os.access()是在某些情況下比os.stat()更好,因爲它檢查是否該文件可以通過執行,根據文件所有者,組和權限。

import os 

for filename in os.listdir('.'): 
    if os.path.isfile(filename) and os.access(filename, os.X_OK): 
     print(filename) 
相關問題