繁体   English   中英

保存输入并在重新启动程序时要求再次使用它

[英]Save input and ask to use it again when restarting program

如何保存用户的输入并在重新启动程序时询问他们是否要再次使用它,这样他们每次关闭程序时都不必输入相同的内容?

您应该将数据存储在某些DBJSON文件中,关闭程序后无法保存存储在变量中的输入数据。

你可以使用这样的东西。 它将用户输入数据保存到config.py模块,因此您可以在任何地方使用它。

import os

user_input = None  
if os.path.exists('config.py'): #check if config file exist
    ask = input("Do you want use previous data? (yes/no)")
    if ask == 'no':
        user_input = input("Some things...")
    elif ask == 'yes':
        import config
        user_input = config.last_input  # take last value of input from config file
    else:
        print("Wrong command, please anserw yes or no.")
else:
    user_input = input("Some things...")

print(user_input)

# save input
with open("config.py", "w+") as file:
    file.write(f"last_input = {user_input}")

这是一种简单的方法,不需要使用 json 或 ini 文件。 你可以复制粘贴这个,就可以了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM