You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求协助为Python脚本添加多登录功能,不同账号对应执行不同代码

Multi-Login Functionality with User-Specific Logic in Python

Got it, let's break down how to add multi-login functionality where different username-password pairs trigger distinct code logic. The cleanest way to handle this is by using a dictionary to map credential pairs to their corresponding functions—this makes it super easy to add/remove users later without rewriting core login code.

Step 1: Define Your User-Specific Logic Functions

First, create separate functions for each user's unique logic. This keeps your code organized and modular.

def handle_xyz_logic():
    """Logic to execute when user xyz logs in"""
    print("Welcome, xyz! Executing your custom logic...")
    # Add your specific code here: API calls, file operations, data processing, etc.

def handle_abc_logic():
    """Logic to execute when user abc logs in"""
    print("Hello, abc! Running your dedicated workflow...")
    # Add your unique code here: report generation, database queries, etc.

Step 2: Map Credentials to Logic

Next, set up a dictionary where each key is a tuple of (username, password), and the value is the function that should run for that user. This creates a clear, maintainable link between credentials and actions.

# Define credential-logic mappings
USER_CREDENTIALS = {
    ("xyz", "zyz"): handle_xyz_logic,
    ("abc", "cba"): handle_abc_logic
}

Step 3: Build the Login Flow

Now create a login function that takes user input, validates against the credential map, and runs the corresponding logic if successful.

def login():
    # Get user input (you could add input masking for passwords in production)
    username = input("Enter username: ").strip()
    password = input("Enter password: ").strip()
    
    # Check if credentials exist in our map
    if (username, password) in USER_CREDENTIALS:
        # Execute the associated logic function
        USER_CREDENTIALS[(username, password)]()
    else:
        print("Invalid username or password. Please try again.")

# Run the login flow when the script is executed directly
if __name__ == "__main__":
    login()

How to Extend This Later

If you need to add more users down the line, it's as simple as:

  • Creating a new function for their unique logic
  • Adding a new (username, password): function entry to the USER_CREDENTIALS dictionary

This approach avoids messy nested if-else chains and keeps your code scalable and easy to read.

内容的提问来源于stack exchange,提问作者Cameron Youell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:43:17