python3:使用用户输入获取模块源代码(检查.getsource)

时间:2018-07-15 17:42:04

标签: python python-3.x

我想做什么...
我有一个名为'my_library.py'的模块,其中包含一些函数或方法。
我还有一个名为'test_library.py'的模块,我想从test_library中打印一些特定功能的源代码,该源代码位于“ my_library”模块中
我知道我们可以用......
        print(inspect.getsource(my_library.add))

         print(open(my_library.__file__).read())
在这里,我想将用户的功能或模块名称作为输入
示例:

    **my_library.py**
    def add(x,y):
        return x+y

    def substract(x,y):
        return x-y

    **test_library.py**
    import inspect
    import my_library
    name = "my_library.substract"
    print(inspect.getsource(name))


TypeError: module, class, method, function, traceback, frame, or code object was expected, got str
我试图将输入的字符串转换为对象,文件,类...似乎没有任何作用
有什么办法可以接受用户的输入并显示该特定功能或模块?
有任何解决问题的建议或建议吗?

预先感谢

2 个答案:

答案 0 :(得分:0)

您需要创建一个实际对象以传递给pinCustomImageName,例如:

CustomPointAnnotation

您可以通过在字符串上使用get_source从字符串生成它们,例如:

In [1]: def add(x,y):
   ...:         return x+y
   ...:

In [2]: def substract(x,y):   return x-y

In [3]: %save my_library.py 1-2
The following commands were written to file `my_library.py`:
def add(x,y):
        return x+y
def substract(x,y):   return x-y

In [4]: import inspect

In [5]: import my_library

In [6]: obj = my_library.substract

In [7]: inspect.getsource(obj)
Out[7]: 'def substract(x,y):   return x-y\n'

In [8]: obj = my_library.add

In [9]: inspect.getsource(obj)
Out[9]: 'def add(x,y):\n        return x+y\n'

In [10]:

礼物:

eval

答案 1 :(得分:0)

说我们有一个文件module.py

def test_func(arg1, arg2):
    return arg1 + arg2

我们可以通过引用函数对象来解析此成员以供getsource()从另一个代码区域使用:

import inspect
import sys
import module

def main():
    # what the user would input
    input_str = 'module.test_func'  
    # split user input up into individual members
    name_list = input_str.split('.')
    # extract the starting point name
    base_name = name_list[0]
    # check to make sure that name exists in the current scope and extract a reference to it
    if base_name in locals():
        base_obj = locals()[base_name]
    elif base_name in globals():
        base_obj = globals()[base_name]
    else:
        print('base name {} is unknown'.format(base_name))
        return 1
    # iteratively step through the attribute chain
    containing_object = base_obj
    for name in name_list[1:]:
        try:
            containing_object = getattr(containing_object, name)
        except AttributeError:
            print('unable to resolve name {} from object {}'.format(name, containing_object))
            return 1
    # print out source of final reference
    print(inspect.getsource(containing_object))
    return 0


if __name__ == '__main__':
    sys.exit(main())

您还可以扩展它,以检索尚未使用importlib导入的模块的成员。