python - 如何在运行时更新 python 程序
问题描述
如果一个程序正在运行,有没有办法在它运行时更新它并让程序响应?Python。
我有一个程序可以更改自己的代码。它接受用户输入并将其添加到程序本身的列表中。之后,可以检查列表中的所有元素。但是,我无法让它在响应中的列表中显示新添加的元素。有没有办法做到这一点,比如调用一个函数但重新调用整个程序(带有更新)?
L = [1, 2, 3]
I = input("Input a number to add to the set")
K = []
global K
with open(__file__, 'r') as f:
S = f.read().split('\n') #split the file into lines, add them to a list
V = S[0].split(' = ')[-1] #take the first line(the list L), take the part after the = sign
M = 1
while V[M] != ']': #this while loop is just a way to access the stuff inside the square brackets without the square brackets
K.append(V[M])
M += 1
N = 'L = [{}, {}]'.format("".join(K), int(I)) #creates the new line to sub in for the first line in the program
with open(__file__, 'w') as f:
f.write('\n'.join([N] + S[1:])) #subs it in
print(L) #to return the list, without the added input. Can it return the list with I added?
我不知道是否有任何方法可以解决这个问题,因为很可能程序一旦开始运行,就无法从不同的文件(或不同版本的文件)运行。但是,如果有办法,我很想听听!
解决方案
首先,使用更好的变量名。
由于您正在使用文件进行写入和读取,请记住,一旦读取,它就会被读入内存。如果要修改文件并读取新数据,则需要关闭文件并再次打开以获取新数据。
您还需要仔细检查您正在读取的嵌套文件的上下文。它指的是同一个文件吗?还是它们是两个不同的文件?
推荐阅读
- android - 由于android中的字节大小不同,某些图像无法从firebase加载
- python - SQLite 从列列表中获取 TOTAL?
- python - 将列表附加到列表时出现意外输出
- python - 如何在 ipdb 中创建条件断点
- java - 如何自动创建类的新实例?
- socrata - Open Payments - 如何协调或解释 API 数据与实时站点可视数据之间的差异
- c++ - C++ 获取运行时间和内存使用情况
- python - 创建一个数据框来详细说明另一个数据框的信息
- node.js - npm install png-img 或 npm install hermione chai 时如何修复错误
- jpa - 如何在 DAO 中为 Primefaces 延迟加载的 DataTable 过滤器实现过滤(包括多选枚举)