Python script accessing own source code

Mirko mirkok.lists at googlemail.com
Wed May 12 15:17:04 EDT 2021


Am 12.05.2021 um 20:41 schrieb Robin Becker:
> .......
>>
>> with open(__file__) as myself:
>>      print(myself.read(), end='')
> 
> very nice, but accessing code that's already seems quite easy. I
> think the real problem is to get a python script name that creates
> and writes itself. So I would ask if any one has the solution to the
> self writing script
> 
> python find-tomorrows-lotto-numbers.py
> 
> since GvR has been shown to have time traveling abilities such a
> script could paradoxically appear acausally.
> -- 
> yrs-not-too-seriously
> Robin Becker


Not sure, if that's what you mean, but writing a self-replicating
script is easy too:

import os
import sys

with open(os.path.abspath(__file__)) as myself:
    with open(sys.argv[1], "w") as yourself:
        yourself.write(myself.read())


Give it a filename as a command-line argument and it will write
itself to that file.


More information about the Python-list mailing list