Python script that prints its source

前端 未结 2 582
春和景丽
春和景丽 2021-01-05 12:43

Is it possible (not necessarly using python introspection) to print the source code of a script?

I want to execute a short python script that also print its source (s

2条回答
  •  囚心锁ツ
    2021-01-05 13:35

    For the most simple answer:

    import my_module
    
    print open(my_module.__file__).read()
    

    I also tried using the inspect package.

    import inspect
    
    import my_module
    
    source_list = inspect.getsourcelines(my_module)
    

    Will give you a list of strings with the source code defined in it

    for line in source_list[0]:
        print line
    

    Will print out the entire source code in a readable manner

提交回复
热议问题