如何实现登录后自动执行文本文件中Python代码的启动器?
Absolutely feasible! This is a standard approach for controlling access to script execution, and it’s totally doable with Python’s built-in tools. Let’s walk through how to build this step by step.
1. Build the Login Verification Module
First, we’ll create a basic login check. For production use, you’ll want to avoid hardcoding credentials (we’ll cover that later), but here’s a simple starting point:
def login(): username = input("Enter your username: ") password = input("Enter your password: ") # In a real app, pull these from environment variables, an encrypted config, or a database valid_credentials = {"admin": "my_secure_pass_123", "dev_user": "dev_access_456"} if username in valid_credentials and valid_credentials[username] == password: print("✅ Login successful! Starting your script...") return True else: print("❌ Invalid username or password. Access denied.") return False
2. Read and Execute the External Python Code File
Once login is confirmed, we need to load and run your target script file. There are two common methods for this:
Method 1: Use exec() for raw text/code files
If your file is just plain text with Python code (e.g., my_script.txt), you can read its content and execute it directly with exec():
def execute_raw_script(script_path): try: with open(script_path, "r") as script_file: script_content = script_file.read() # Execute the loaded code exec(script_content) print("✅ Script executed successfully!") except FileNotFoundError: print(f"❌ Error: Could not find script file at {script_path}") except Exception as e: print(f"❌ Error running script: {str(e)}")
Method 2: Use importlib for standard Python modules
If your file is a proper .py module (with functions/classes), using importlib is a cleaner, more maintainable approach:
import importlib.util def execute_as_module(script_path): try: # Create a module spec from the file spec = importlib.util.spec_from_file_location("user_script", script_path) user_script = importlib.util.module_from_spec(spec) # Execute the module spec.loader.exec_module(user_script) print("✅ Module executed successfully!") except FileNotFoundError: print(f"❌ Error: Could not find script file at {script_path}") except Exception as e: print(f"❌ Error running module: {str(e)}")
3. Combine Everything into a Launcher
Now tie the login and execution logic together in a main function:
def main(): if login(): # Replace this with the path to your script file target_script = "./my_python_code.txt" # or "./my_module.py" # Choose execution method based on your file type execute_raw_script(target_script) # execute_as_module(target_script) if __name__ == "__main__": main()
Critical Security Notes
- Never execute untrusted code: Both
exec()and dynamic import will run any code in the target file. If the file is tampered with, it could execute malicious actions. - Avoid hardcoding credentials: Store usernames/passwords in environment variables (use
os.getenv("APP_USER")) or encrypted storage, not directly in your code. - Lock down script file permissions: On Linux/macOS, use
chmod 600 your_script.pyto ensure only your user can read/write the file. On Windows, set file permissions to restrict access.
内容的提问来源于stack exchange,提问作者26099

