Python script that prints its source

前端 未结 2 583
春和景丽
春和景丽 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:31

    As long as you're not doing anything crazy with packages, put this at the top of your script

    with open(__file__) as f:
        print f.read()
    

    Which will read in the current file and print it out.

    For python 3 make sure to use instead print(f.read())

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题