首页 > 解决方案 > 如何在运行时更新 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?

我不知道是否有任何方法可以解决这个问题,因为很可能程序一旦开始运行,就无法从不同的文件(或不同版本的文件)运行。但是,如果有办法,我很想听听!

标签: python

解决方案


首先,使用更好的变量名。

由于您正在使用文件进行写入和读取,请记住,一旦读取,它就会被读入内存。如果要修改文件并读取新数据,则需要关闭文件并再次打开以获取新数据。

您还需要仔细检查您正在读取的嵌套文件的上下文。它指的是同一个文件吗?还是它们是两个不同的文件?


推荐阅读