如何在运行时更新python程序

问题描述 投票:1回答:1

如果程序正在运行,是否可以在运行时进行任何更新并让程序响应? 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
1个回答
0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.