简体   繁体   English

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

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

How can I save a user's input and ask them if they want to use it again when restarting the program, so they don't have to enter the same thing every time they close the program?如何保存用户的输入并在重新启动程序时询问他们是否要再次使用它,这样他们每次关闭程序时都不必输入相同的内容?

You should store the data in some DB or JSON file, there is no way to save input data stored in a variable after closing the program.您应该将数据存储在某些DBJSON文件中,关闭程序后无法保存存储在变量中的输入数据。

You can use something like this.你可以使用这样的东西。 It's save user input data to config.py module, so you can use it anywhere.它将用户输入数据保存到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}")

It's easy way, not needed to use json or ini files.这是一种简单的方法,不需要使用 json 或 ini 文件。 You can just copy&paste this, will work.你可以复制粘贴这个,就可以了。

暂无
暂无

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

相关问题 输入错误时,如何再次请求相同的输入? - How can I ask for the same input again when there was incorrect input? 如果引发异常,请再次输入 - If an exception is raised ask again for input 重新启动程序时发送终端输入数据(python) - Send terminal input data when restarting a program (python) 编写一个程序,提示输入一个整数并打印 int,如果输入了其他任何内容,则再次询问,直到输入一个整数 - Write a program that prompts for an integer and prints the int, if anything else is entered ask again till a integer is input 如果第二个输入错误,再次询问第一个输入 - ask again for first input if second input is wrong 如何从程序中保存信息,然后使用它在程序中再次显示(简单编程) - How to save information from the program then use it to show in program again (simple programming) 根据用户在Python上的输入重新启动程序? - Restarting my program based on user input on Python? 如何使用输入 function 来询问路径名并将其保存在双引号而不是单引号中? - How can I use the input function to ask for the Pathname and save it within double quotes instead of single quotes? 尝试要求输入文件并将其保存在特定位置 - Trying to ask for a file input and save it in specific location 在绘制线性方程时,如何让我的程序询问用户输入 - How to make my program ask for user input when graphing linear equations
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM