我如何了解一个给定的Python模块的源文件安装在哪里?Windows上的方法和Linux上的方法不同吗?

我特别试图寻找datetime模块的源代码,但我对更一般的答案也感兴趣。


当前回答

在python解释器中,您可以导入特定的模块,然后键入help(module)。这将提供诸如名称、文件、模块文档、描述等详细信息。

Ex:

import os

help(os)


Help on module os:

NAME

os - OS routines for Mac, NT, or Posix depending on what system we're on.

FILE

/usr/lib/python2.6/os.py

MODULE DOCS

http://docs.python.org/library/os

DESCRIPTION

This exports:

- all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc.

- os.path is one of the modules posixpath, or ntpath

- os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos'

等人

其他回答

看看这个漂亮的"cdp"命令,cd到包含指定Python模块源代码的目录:

cdp () {
  cd "$(python -c "import os.path as _, ${1}; \
    print _.dirname(_.realpath(${1}.__file__[:-1]))"
  )"
}

对于那些更喜欢GUI解决方案的人:如果你正在使用GUI,如Spyder (Anaconda安装的一部分),你可以右键单击模块名称(如“import csv”中的“csv”),并选择“go to definition”-这将打开文件,但在顶部你可以看到确切的文件位置(“C:....csv.py”)

在python解释器中,您可以导入特定的模块,然后键入help(module)。这将提供诸如名称、文件、模块文档、描述等详细信息。

Ex:

import os

help(os)


Help on module os:

NAME

os - OS routines for Mac, NT, or Posix depending on what system we're on.

FILE

/usr/lib/python2.6/os.py

MODULE DOCS

http://docs.python.org/library/os

DESCRIPTION

This exports:

- all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc.

- os.path is one of the modules posixpath, or ntpath

- os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos'

等人

datetime是一个内置模块,因此没有(Python)源文件。

对于来自.py(或.pyc)文件的模块,可以使用mymodule。__file__。

> import random
> random.__file__
'C:\\Python25\\lib\\random.pyc'

如果你没有使用解释器,那么你可以运行下面的代码:

import site
print (site.getsitepackages())

输出:

['C:\\Users\\<your username>\\AppData\\Local\\Programs\\Python\\Python37', 'C:\\Users\\<your username>\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages']

Array中的第二个元素将是包的位置。在这种情况下:

C:\Users\<your username>\AppData\Local\Programs\Python\Python37\lib\site-packages