runtime - How can I make a python script change itself? -


how can make python script change itself?

to boil down, have python script (run.py)like this

a = 0 b = 1 print + b # here such first line of script reads = 1 

such next time script run like

a = 1 b = 1 print + b # here such first line of script reads = 2 

is in way possible? script might use external resources; however, should work running 1 run.py-file.

edit: may not have been clear enough, script should update itself, not other file. sure, once allow simple configuration file next script, task trivial.

answer:

it easier thought. @khelwood 's suggestion works fine, opening script , writing it's own content unproblematic. @gerrat's solution works nicely. how i'm having it:

# -*- coding: utf-8 -*- = 0 b = 1 print + b  content = [] open(__file__,"r") f:     line in f:         content.append(line)  open(__file__,"w") f:     content[1] = "a = {n}\n".format(n=b)     content[2] = "b = {n}\n".format(n=a+b)     in range(len(content)):         f.write(content[i]) 

for example (changing value of a each time run):

a = 0 b = 1 print + b  open(__file__, 'r') f:     lines = f.read().split('\n')     val = int(lines[0].split(' = ')[-1])     new_line = 'a = {}'.format(val+1)     new_file = '\n'.join([new_line] + lines[1:])  open(__file__, 'w') f:     f.write('\n'.join([new_line] + lines[1:])) 

Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -