Python script accessing own source code

Stestagg stestagg at gmail.com
Wed May 12 13:35:16 EDT 2021


On 2021-05-12 15:48, Michael F. Stemper wrote:

> > On 12/05/2021 08.26, Dino wrote:
> >
> >> Hi, here's my (probably unusual) problem. Can a Python (3.7+) script
> >> access its own source code?
> >
> > Here is a fairly simple python program that reads itself:
> >
> > ================================================
> > #!/usr/bin/python
> >
> > import sys
> >
> > with open( sys.argv[0], "rt" ) as myself:
> >     for line in myself:
> >       junk = sys.stdout.write( "%s" % (line) )
> >
> > sys.exit(0)
> > ================================================
> >
> > It's not bullet-proof. If you put it in a directory in your $PATH and
> > run it from somewhere else, it won't work.
> >
>
>
Here's a fairly simple option:

==========
import inspect
import sys

print(inspect.getsource(sys.modules[__name__]))
========


More information about the Python-list mailing list