Python script accessing own source code

MRAB python at mrabarnett.plus.com
Wed May 12 12:49:15 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.
> 
How about this:

with open(__file__) as myself:
     print(myself.read(), end='')


More information about the Python-list mailing list