ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

python用户账户管理

2026/9/12 6:36:52 拓冰建站 浏览量
python用户账户管理

在Python中,可以使用标准库中的getpassos模块以及第三方库如flask来实现用户账户管理。

以下是一个简单的示例,演示如何使用getpassos模块来创建和验证用户账户:

import getpass
import osdef create_account():username = input("Enter username: ")password = getpass.getpass("Enter password: ")os.system(f"echo 'username={username}, password={password}' > account.txt")print("Account created successfully!")def validate_account():username = input("Enter username: ")password = getpass.getpass("Enter password: ")with open("account.txt", "r") as f:account_info = eval(f.read())if account_info['username'] == username and account_info['password'] == password:print("Account validation successful!")else:print("Account validation failed!")while True:print("\nWelcome to the user account management system!")print("1. Create account")print("2. Validate account")print("3. Exit")choice = input("Enter your choice (1-3): ")if choice == '1':create_account()elif choice == '2':validate_account()elif choice == '3':breakelse:print("Invalid choice, please try again.")

在上面的代码中,我们首先定义了两个函数create_account()validate_account(),分别用于创建和验证用户账户。在创建账户时,我们使用getpass.getpass()函数来获取用户输入的密码,并将其与用户名一起存储在名为account.txt的文件中。在验证账户时,我们再次使用getpass.getpass()函数来获取用户输入的密码,并从文件中读取账户信息,然后将其与输入的用户名和密码进行比较。如果它们匹配,则验证成功。否则,验证失败。在主循环中,我们显示一个菜单,并根据用户的输入调用相应的函数。