gpt4 book ai didi

python - 如何在Python程序运行时更新它

转载 作者:太空宇宙 更新时间:2023-11-03 20:10:34 46 4
gpt4 key购买 nike

如果程序正在运行,是否有任何方法可以在其运行时更新它并使程序做出响应? 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 - 如何在Python程序运行时更新它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58741572/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com