How can I make a python script change itself?

坚强是说给别人听的谎言 提交于 2019-11-30 14:58:43

问题


How can I make a python script change itself?

To boil it down, I would like to have a python script (run.py)like this

a = 0
b = 1
print a + b
# do something here such that the first line of this script reads a = 1

Such that the next time the script is run it would look like

a = 1
b = 1
print a + b
# do something here such that the first line of this script reads a = 2

Is this in any way possible? The script might use external resources; however, everything should work by just running the one run.py-file.

EDIT: It may not have been clear enough, but the script should update itself, not any other file. Sure, once you allow for a simple configuration file next to the script, this task is trivial.

Answer:

It is actually much easier than thought. @khelwood 's suggestion works just fine, opening the script and writing it's own content to it is completely unproblematic. @Gerrat's solution also works nicely. This is how I'm having it:

# -*- coding: utf-8 -*-
a = 0
b = 1
print a + b

content = []
with open(__file__,"r") as f:
    for line in f:
        content.append(line)

with open(__file__,"w") as f:
    content[1] = "a = {n}\n".format(n=b)
    content[2] = "b = {n}\n".format(n=a+b)
    for i in range(len(content)):
        f.write(content[i])

回答1:


For an example (changing the value of a each time its run):

a = 0
b = 1
print a + b

with open(__file__, 'r') as 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:])

with open(__file__, 'w') as f:
    f.write('\n'.join([new_line] + lines[1:]))



回答2:


Make a file a.txt that contains one character on one line:

0

Then in your script, open that file and retrieve the value, then immediately change it:

with open('a.txt') as f:
    a = int(f.read())
with open('a.txt', 'w') as output:
    output.write(str(a+1))
b = 1
print a+b

On the first run of the program, a will be 0, and it will change the file to contain a 1. On subsequent runs, a will continue to be incremented by 1 each time.




回答3:


What you're asking for would require you to manipulate files at the {sys} level; basically, you'd read the current file in, modify it, over-write it, and reload the current module. I played with this briefly because I was curious, but I ran into file locking and file permission issues. Those are probably solvable, but I suspect that this isn't really what you want here.

First: realize that it's generally a good idea to maintain a separation between code and data. There are exceptions to this, but for most purposes, you'll want to make the parts of your program that can change at runtime read their configuration from a file, and write changes to that same file.

Second: idomatically, most python projects use YAML for configuration

Here's a simple script that uses the yaml library to read from a file called 'config.yaml', and increments the value of 'a' each time the program runs:

#!/usr/bin/python
import yaml

config_vals = ""
with open("config.yaml", "r") as cr:
   config_vals = yaml.load(cr)

a = config_vals['a']
b = config_vals['b']
print a + b

config_vals['a'] = a + 1
with open("config.yaml", "w") as cw:
   yaml.dump(config_vals, cw, default_flow_style=True)

The runtime output looks like this:

$ ./run.py
3 
$ ./run.py
4
$ ./run.py
5 

The initial YAML configuration file looks like this:

a: 1
b: 2


来源:https://stackoverflow.com/questions/39643428/how-can-i-make-a-python-script-change-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!