2009-04-08 30 views
41

Làm cách nào tôi có thể lấy đường dẫn tệp của mô-đun được nhập bằng python. Tôi đang sử dụng Linux (nếu nó quan trọng).Lấy đường dẫn tệp của mô-đun đã nhập

Ví dụ: nếu tôi đang ở trong thư mục chính của mình và nhập mô-đun, nó sẽ trả về đường dẫn đầy đủ của thư mục chính của tôi.

+2

trùng lặp: http://stackoverflow.com/questions/247770/retrieving -python-module-path –

Trả lời

6

này sẽ cung cấp cho bạn các thư mục module là:

import foo 
os.path.dirname(foo.__file__) 
52

Modules và các gói có một thuộc tính __file__ rằng có thông tin đường đi của nó. Nếu mô-đun được nhập tương đối so với thư mục làm việc hiện tại, có thể bạn sẽ muốn có đường dẫn tuyệt đối.

import os.path 
import my_module 

print os.path.abspath(my_module.__file__) 
9

Tôi đã sử dụng này:

import inspect 
import os 
class DummyClass: pass 
print os.path.dirname(os.path.abspath(inspect.getsourcefile(DummyClass)) 

(Edit: This is a "tôi đang ở đâu" chức năng - nó sẽ trả về thư mục chứa các module hiện tại tôi không hoàn toàn chắc chắn nếu. đó là những gì bạn muốn).

5

Để tìm ra con đường tải các module đã nạp:

>>> import sys 
>>> sys.modules['os'] 
<module 'os' from 'c:\Python26\lib\os.pyc'> 
+0

Hoặc, chỉ cần đặt, '>>> os'. Bạn đang dựa vào 'str()' đại diện của module. – YvesgereY

1

Tôi đã sử dụng phương pháp này, trong đó áp dụng cho cả các module tích hợp không được xây dựng trong và:

def showModulePath(module): 
     if (hasattr(module, '__name__') is False): 
      print 'Error: ' + str(module) + ' is not a module object.' 
      return None 
     moduleName = module.__name__ 
     modulePath = None 
     if imp.is_builtin(moduleName): 
      modulePath = sys.modules[moduleName]; 
     else: 
      modulePath = inspect.getsourcefile(module) 
      modulePath = '<module \'' + moduleName + '\' from \'' + modulePath + 'c\'>' 
     print modulePath 
     return modulePath 

Ví dụ:

Utils.showModulePath(os) 
Utils.showModulePath(cPickle) 

Kết quả:

<module 'os' from 'C:\SciSoft\WinPython-64bit-2.7.10.3\python-2.7.10.amd64\lib\os.pyc'> 
<module 'cPickle' (built-in)> 
0

Tôi có thể bị trễ ở đây, một số mô-đun sẽ thông qua AttributeError khi sử dụng thuộc tính __file__ để tìm đường dẫn. Trong trường hợp đó, người ta có thể sử dụng __path__ để lấy đường dẫn của mô-đun.

>>> import some_module 
>>> somemodule.__path__ 
['/usr/lib64/python2.7/site-packages/somemodule'] 
0

Hãy thử:

giúp đỡ ('xxx')

Ví dụ

>>> help(semanage) 
Help on module semanage: 

NAME 
    semanage 

FILE 
    /usr/lib64/python2.7/site-packages/semanage.py 
Các vấn đề liên quan