Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a python script write into itself [closed]

Tags:

python

I am creating a simple AI program in Python 2.7 and i was going to make it be able to learn. Is there any way to have it so the script could edit itself, like adding a answer to a question into it's own code, in a certain spot in the code.

thank-you in advance guys!

like image 475
Calder Hutchins Avatar asked Dec 15 '22 06:12

Calder Hutchins


2 Answers

When a Python interpreter is invoked on a script, it is parses and transforms it into byte-code.. this leaves a .pyc file which is actually what executed.

A script could write into itself but that would not cause parsing to restart.

like image 94
Spaceghost Avatar answered Dec 30 '22 23:12

Spaceghost


You could open the file containing the code using:

module = __import__(__name__)
with open(module.__file__) as f:
    print f.read()

Although it is not recommended to dynamically alter the source code.

like image 28
Remco Haszing Avatar answered Dec 30 '22 21:12

Remco Haszing