Python script accessing own source code

Michael F. Stemper mstemper at gmail.com
Wed May 12 10:48:55 EDT 2021


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.

-- 
Michael F. Stemper
I feel more like I do now than I did when I came in.


More information about the Python-list mailing list