如何从Python命令行查找定义函数的文件

时间:2014-05-21 00:06:10

标签: python file-location

我想说我想在Python中探索import语句。如何从Python命令行中找到定义import的文件?注意我在Windows 7中使用Python 2.7.6(iPython)。

对于大多数对象,只需输入对象名即可。例如:

import os
os

产生以下内容:

<module 'os' from 'C:\Anaconda\lib\os.pyc'>

但是你不能对import等基本命令做同样的事情。

我试过搜索我的Python文件夹,但不出所料,我没有像C:\Anaconda\lib\import.py这样简单的东西。有没有一种简单的方法可以找出定义这些语句的位置(我很多时候会在c代码中意识到,但这就是我所追求的)?

更新(2014年5月27日)

似乎人们认为使用内置命令无法以任何简单的方式完成。但是,如果你的生活依赖于它,你可以用Python编写一些不优雅的grep-type函数,不是吗?

2 个答案:

答案 0 :(得分:1)

importmodule的方式不同os。相反,它是statement

https://docs.python.org/2/reference/simple_stmts.html#import

答案 1 :(得分:0)

导入后致电os时,会将路径打印到文件中,因为它是模块。相反,import是一个声明:

>>> import math
>>> math
<module 'math' from '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/math.so'>
>>> import
  File "<stdin>", line 1
    import
         ^
SyntaxError: invalid syntax
>>> 

万一你觉得你需要知道,以下是其他陈述,当他们被称为空白时做类似的事情:

>>> with
  File "<stdin>", line 1
    with
       ^
SyntaxError: invalid syntax
>>> yield
  File "<stdin>", line 1
SyntaxError: 'yield' outside function
>>> return
  File "<stdin>", line 1
SyntaxError: 'return' outside function
>>> continue
  File "<stdin>", line 1
SyntaxError: 'continue' not properly in loop
>>> import
  File "<stdin>", line 1
    import
         ^
SyntaxError: invalid syntax
>>> raise
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType
>>> assert
  File "<stdin>", line 1
    assert
         ^
SyntaxError: invalid syntax
>>> del
  File "<stdin>", line 1
    del
      ^
SyntaxError: invalid syntax
>>> break
  File "<stdin>", line 1
SyntaxError: 'break' outside loop
>>>