python - 如何在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?

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

最佳答案

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

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

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

关于python - 如何在Python程序运行时更新它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58741572/

相关文章:

Python robotparser 模块不会加载 'robots.txt'

python - 在不同行中打印列表中的多个项目

python - 如何使用 Anaconda 的 Python 版本执行 Python 脚本?

python - 以 django 形式强制

python - 确保至少安装了一个额外的 Python 包

python - BeautifulSoup: TypeError: 'NoneType' 对象不可订阅

python - 为什么会出现内存错误? Python

python - 如何使用字符串中的位置来更改 Pandas Dataframe 列中的每个字符串

python - 子进程 stdout/stderr 到有限大小的日志文件

python - 根据 Pandas DataFrame 中的元素从另一个 DataFrame 中获取元素