简体   繁体   English

如何使 python 脚本自行更改?

[英]How can I make a python script change itself?

How can I make a python script change itself?如何使 python 脚本自行更改?

To boil it down, I would like to have a python script ( run.py )like this归根结底,我想要一个 python 脚本( run.py ),就像这样

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.然而,一切都应该通过运行一个run.py文件来工作。

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.当然,一旦您允许脚本旁边有一个简单的配置文件,这个任务就很简单了。

For an example (changing the value of a each time its run): 举一个例子(改变的值a每次其运行):

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:]))

What you're asking for would require you to manipulate files at the {sys} level; 您要的是要求您在{sys}级别上操作文件; 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 第二:从理论上讲,大多数python项目使用YAML进行配置

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: 这是一个简单的脚本,该脚本使用yaml库从名为“ config.yaml”的文件中读取,并在程序每次运行时递增“ a”的值:

#!/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: 初始YAML配置文件如下所示:

a: 1
b: 2

Gerrat's code but modified. Gerrat 的代码但已修改。

#some code here
a = 0
b = 1

print(a + b)

applyLine = 1#apply to wich line(line 1 = 0, line 2 = 1)
with open(__file__, 'r') as f:
  lines = f.read().split('\n')#make each line a str in a list called 'lines'
  val = int(lines[applyLine].split(' = ')[-1])#make an int to get whatever is after ' = ' to applyed line 
  new_line = 'a = {}'.format(val+1)#generate the new line
lines[applyLine] = new_line#update 'lines' to add the new line
write = "\n".join(lines)#create what to rewrite and store it in 'write' as str
with open(__file__, 'w') as f:
  f.write(write)#update the code

Make a file a.txt that contains one character on one line: 使文件a.txt包含一行字符:

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 . 在程序的第一次运行中, a将为0 ,它将更改文件以使其包含1 On subsequent runs, a will continue to be incremented by 1 each time. 在随后的运行中, a将继续以每次1递增。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM