krakatoa
Posts: 5
Joined: Tue Feb 05, 2019 9:30 am

Can a python script edit itself?

Sun Mar 15, 2020 1:35 am

Hi
Before I try it, I would like to know if a python script can edit itself? that is write , edit or delete new code to its self. would the script have to change its own permissions?

Thanks D.

Garvan
Posts: 41
Joined: Sun Jan 05, 2020 9:59 am

Re: Can a python script edit itself?

Sun Mar 15, 2020 5:59 am

You should just try it, it would be quicker than asking, but it wont work the way you are hoping. The python source code is loaded into memory on start, so any edits you make to the source will not be executed until the program is run a second time.

pfletch101
Posts: 623
Joined: Sat Feb 24, 2018 4:09 am
Location: Buffalo, NY, USA

Re: Can a python script edit itself?

Mon Mar 16, 2020 12:49 am

As garvan says, it can be done without too much difficulty, but the currently executing copy of the code is unaffected. A more usual way of modifying the behavior of a running script is an appropriate conditional within the script! :) Of course, If you have a script that is scheduled to run periodically and you want to change what it does on its next run, you could do what you propose. Even here, though, a better approach might be to create one or more persistent 'flag' file(s) and have the script behave differently according to which file(s) is/are present.

Return to “Beginners”