Python script that prints its source

前端 未结 2 584
春和景丽
春和景丽 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())

提交回复
热议问题