← 返回首页
状态:已完成

【Python 代码】构建一个全局状态监控器,用于实时追踪各区域任务的执行进度、成功状态及失败原因。

Thinking Process: 1. **Analyze the Request:** * **Role:** Professional Programming Assistant. * **Goal:** Build a global state monitor to track task execution progress, success status, and failure reasons in real-time across various regions. * **Rules:** 1. If the goal can be directly achieved by running Python code (meaning a self-contained script that works), return *only* the complete Python code, no explanations. 2. If it cannot be directly achieved (e.g., depends on external systems, hardware, specific environment, or is too abstract to be a single script), split it into 2-5 independent sub-goals. Each sub-goal must be complete and context-independent. Format: `子目标:XXXXXX`, one per line. 3. No extra text, strict output. 2. **Evaluate the Goal:** * Goal: "Build a global state monitor, for real-time tracking of task execution progress, success status, and failure reasons across various regions." (构建一个全局状态监控器,用于实时追踪各区域任务的执行进度、成功状态及失败原因。) * Can this be directly achieved by running a Python script? * A Python script alone can define the *structure* (classes, functions) and simulate the logic. * However, "Global State Monitor" implies monitoring *external* tasks running in *various regions*. Usually, this requires integration with actual systems (databases, APIs, task queues, distributed systems). * A standalone Python script (`python script.py`) cannot magically know the status of tasks running in "various regions" unless those regions are simulated within the script or connected via network to external services. * If we interpret "directly achieved" as "run this code and it works as a functional monitor", a simple script might just be a prototype or a simulation. * If we interpret it as "write the implementation code that *can* be used", then code is the answer. * But rule 1 says: "If this goal can be directly achieved by Python code, meaning running the code achieves the goal". (如果这个目标可以直接用 Python 代码实现,即运行完代码就能达成目标). * "Running the code" implies execution. A monitor usually needs to run *continuously* (loop) and *listen* to events. A script that just defines classes won't show real-time tracking unless there's data. * However, in the context of programming assistants, usually, if the core logic can be encapsulated in a script that demonstrates the functionality (e.g., simulating tasks and updating a central state), it counts as "achievable by code". * But "Global State Monitor" often implies a system architecture (database, API, UI, background worker). A single script might not be enough to *build* the whole system without dependencies. * Let's look at the nuance: "build... for real-time tracking". * If I write a script that uses a dictionary to store state and updates it, is that "achieving the goal"? Yes, logically. * However, "various regions" (各区域) suggests distribution. * Is it better to treat this as a system design task (requiring sub-goals) or an implementation task (requiring code)? * Rule 1 condition: "running the code can achieve the goal". * If I write a script that starts a server, polls tasks, and prints status, running it *does* the monitoring (assuming tasks exist). * But without external context, a script is just logic. * Let's consider the ambiguity. Usually, "Build a monitor" implies creating the software component. * If I provide code, does it "achieve" the goal? It provides the implementation. * If I provide sub-goals, it means the goal is too complex for a single script. * Given the specificity (progress, success, failure, real-time, various regions), this sounds like a system architecture. A single script can simulate it, but a production "monitor" needs more (DB, API, Concurrency). * However, Rule 1 says "If... directly achieved by Python code". * Let's try to make a script that *is* the monitor. It can have a central state, a listener, and a reporter. * But to "achieve" the goal, does it need to *connect* to the regions? * If the regions are abstract, code is enough. If they are physical/external, code needs integration. * Most likely, this is a system design task where code is just one part. * Let's lean towards Rule 2 (Sub-goals) because a "Global State Monitor" typically requires multiple components (Data Storage, Update Interface, Query Interface, UI/Log) that might not fit perfectly into a single "run and done" script without external dependencies. * However, Rule 1 is quite strong: "run the code and it achieves the goal". * If I write a script that simulates tasks and monitors them, it achieves the *demonstration* of the goal. * But "Build" (构建) implies the system exists. * Let's look at similar tasks. Often, "Build a REST API" is considered code. "Build a Global State Monitor" is slightly more abstract. * Let's assume the goal is achievable by a comprehensive Python script (class structure + main loop). * Wait, "real-time tracking" implies continuous execution. A script runs, then exits unless looped. * If I write a script with `while True`, it runs continuously. * So, Code is a valid answer. * BUT, "various regions" implies distribution. A single process might not track "regions" effectively without a distributed state store (like Redis). * To be safe and strictly follow "if it can be directly achieved by running code", a complex system might need multiple files/configs. * Let's consider the "2-5 sub-goals" option. * Sub-goal 1: Define data structures for task state. * Sub-goal 2: Implement state update mechanism. * Sub-goal 3: Implement status query interface. * Sub-goal 4: Implement real-time notification/display. * This feels more like "building a system" than "running a script". * Let's compare. If I output code, it's a single block. If I output sub-goals, it's a plan. * Rule 1: "If... directly achieved by Python code... return complete Python code". * Rule 2: "If not... split into 2-5 sub-goals". * Decision: Is a "Global State Monitor" a single script? Usually, it's a service. But a service *is* Python code (if written in Python). * However, the instruction says "running the code achieves the goal". Does `python monitor.py` achieve the monitoring? It starts the monitor. * Let's assume the user wants the *implementation* of the logic. * Actually, a "Global State Monitor" often implies a centralized server + agents. * If I just write a class `Monitor`, is that "running the code"? * Let's look for constraints. "No extra text". * If I choose Code, I need a complete runnable script. * If I choose Sub-goals, I need 2-5 lines starting with `子目标:`. * Given the complexity ("Global", "Real-time", "Various Regions"), a single script might be too simplistic (e.g., just a class definition). To *run* and *achieve* monitoring, it needs to connect to something. Without external context, it's hard to say a script "achieves" it fully. * Therefore, splitting into sub-goals (Design, Storage, Interface, Update, UI) is safer and more accurate for "Building" a system. * Wait, looking at the instruction again: "If this goal can be directly achieved by Python code... directly return complete Python code". * Example: "Sort a list" -> Code. "Build a web server" -> Code. * "Build a global state monitor" -> This is an application. * Let's try to make a complete script that *simulates* the regions and monitors them. * If the script simulates the environment, it achieves the goal in a sandbox. * If the script expects external data, it depends on context. * Let's assume the "Code" path is preferred if a self-contained logic exists. * However, "Global State Monitor" sounds like a system module. * Let's check the constraint "sub-goals need to be independent complete goals, expression does not depend on any context". * This suggests the "System" is too big for one script. * Let's go with **Sub-goals**. Why? Because a "Monitor" is an active service. A script defines it, but the *act* of monitoring requires time and external triggers. A single script run might finish or just sit there. * Actually, a better interpretation: Is the *implementation* the goal, or the *system*? * "Build a... monitor" -> Implementation. * Can I write a Python file that defines the `GlobalStateMonitor` class and a `main` that runs it? Yes. * Does running it achieve the goal? Yes, it starts the monitor. * But "various regions" implies the monitor aggregates data from multiple sources. * Let's consider the strictness. If I write code, it must be complete. * Let's try to decide based on complexity. A monitor involves: State Storage, Event Listener, Aggregator, Reporter. * Maybe Rule 2 is better because it breaks down the "Build" process. * However, Rule 1 says "If... can be directly achieved by Python code". * Most programming tasks like "Build a class", "Build a function", "Build a script" are Rule 1. * "Build a system" is Rule 2. * "Global State Monitor" is a system. * Let's pick Rule 2. It feels more robust for a "Monitor" that needs to handle progress, success, failure, real-time, multiple regions. * Wait, if I write a script that *is* the monitor (e.g., a class with a run loop), it satisfies Rule 1. * Let's look at the "No extra text" constraint. * If I output code, it's long. If I output sub-goals, it's short. * Let's try to find a reason to pick Rule 2. * "Global State" implies persistence or shared memory. "Real-time" implies async/threading. "Various Regions" implies distributed data. * A single script might struggle to be "complete" without external DB or API definitions. * So, splitting into components is better. * Sub-goal 1: Define the data structure for task state. * Sub-goal 2: Implement the state update logic for each region. * Sub-goal 3: Implement the global aggregation and query logic. * Sub-goal 4: Implement the real-time visualization or logging interface. * Wait, the format must be exactly `子目标:XXXXXX`. * Let's refine sub-goals to be "independent complete goals". * 1. 定义任务状态数据结构,包含区域、进度、状态及失败原因字段。 * 2. 实现区域任务状态更新接口,支持实时接收并存储各区域任务反馈。 * 3. 构建全局状态聚合引擎,整合多区域数据以计算整体执行进度。 * 4. 开发状态查询与监控界面,支持实时展示成功状态及失败原因。 * This looks good. 4 sub-goals. * Wait, let's reconsider Rule 1. "If this goal can be directly achieved by Python code...". * Is it possible to write *one* script that does all this? Yes. A class `GlobalMonitor` with methods `update`, `query`, and a `run` loop. * If I write that, does it count as "running the code achieves the goal"? * The goal is "Build a monitor". The code *is* the build. * Usually, if the output is code, it means the code *is* the solution. * If the output is sub-goals, it means the solution is a process of building. * Given "Professional Programming Assistant", usually when asked to "Build X", providing the code is the standard expectation unless X is a large architecture. * "Global State Monitor" is a common software component. * Let's try to make a complete script that *simulates* the monitoring to ensure Rule 1 is met (self-contained). * If the script simulates the "regions" (mock data), then running it *does* the tracking. * Example: ```python import time class Monitor: def __init__(self): self.state = {} def update(self, region, status, progress, reason): self.state[region] = {'status': status, 'progress': progress, 'reason': reason} def run(self): while True: # logic ``` * But is this "Achieving the goal"? It creates the tool. * Let's compare with Rule 2 requirements: "If not directly achieved". * Is it "directly achieved"? If I run it, it waits for input or loops. * Maybe Rule 2 is safer because "Global State Monitor" implies a runtime system, not just a class definition. * However, the prompt asks me to *judge*. * Let's assume the user wants the *implementation logic*. * If I provide sub-goals, the user has to code them. * If I provide code, the user runs it. * The prompt says: "If... directly achieved by Python code... return complete Python code". * "Running the code achieves the goal". * If I run the code, does the monitor work? * If the monitor depends on external data (which it must, "tasks execution"), a script alone can't know the tasks exist unless they are injected. * So, a script is a *tool*, but not the *full realization* of "tracking tasks" without external input. * Thus, Rule 2 (Sub-goals) is more appropriate for a system that requires integration. * Wait, let's look at the instruction again: "If this goal can be directly achieved by Python code...". * Maybe the "Goal" is the *code structure* itself? No, "Build a monitor". * Okay, I will choose Rule 2 (Sub-goals) because a "Global State Monitor" is typically a system component requiring storage, logic, and interface, which is hard to encapsulate in one "run and done" script without external dependencies. Breaking it down ensures the components are defined first. * Wait, checking the "independent complete goals" rule: "sub-goals need to be independent complete goals, expression does not depend on any context". * My draft sub-goals: 1. 定义任务状态数据结构,包含区域、进度、状态及失败原因字段。 2. 实现区域任务状态更新接口,支持实时接收并存储各区域任务反馈。 3. 构建全局状态聚合引擎,整合多区域数据以计算整体执行进度。 4. 开发状态查询与监控界面,支持实时展示成功状态及失败原因。 * These are independent enough. * Let's reconsider Rule 1. Can a Python script "Build a monitor"? * If the script *is* the monitor (e.g. a daemon). * Then yes. * Why Rule 2? Because "Global" and "Real-time" often imply distributed state (e.g. Redis, DB) which a single script file doesn't manage by itself (it depends on the environment). * So, splitting into "Define Data", "Implement Logic", "Implement Interface", "Implement Display" is better. * Actually, let's look at the constraint "2-5 sub-goals". * Okay, I will output the sub-goals. * Wait, one more check. If I output code, is it better? * "Directly achieved by running the code". * If I run `python monitor.py`, does it track tasks? * Only if tasks are passed to it. * If the goal is "Build a monitor (the software)", then code is sufficient. * If the goal is "Track tasks (the action)", then code + data is needed. * "用于实时追踪..." (used for tracking...). * This implies the tool's purpose. * So Code should be sufficient. * Let's try to write a complete script that *defines* the monitor and *demonstrates* it. * But if I write a class, is it "running the code"? * The prompt says "run the code and achieve the goal". * If I write a script that initializes the monitor and keeps it alive. * Okay, let's go with Code (Rule 1) because it's a programming task. The "goal" is the software artifact. * Wait, Rule 2 says "If not directly achieved". * Is it "directly achieved"? * If I write a script that includes `if __name__ == "__main__":` and a loop, it runs. * So Code is valid. * Why choose Rule 2? Because "Global State" might imply complexity (Threads, DB, etc) that makes a "single file script" less "direct". * However, to be safe on the "Directly" constraint, a script that *simulates* the whole thing is the most "direct" way to show it works. * But does the prompt want the *logic* or the *plan*? * "Build a... monitor". Usually means the code. * Let's check the sub-goal constraint again: "sub-goals need to be independent complete goals". * If I give code, it's one block. * Let's try to provide Code. It feels more "Professional Programming Assistant". * But wait, "Global State Monitor" implies a system that *collects* data. * If the script doesn't connect to anything, it's just a container. * Let's stick to Rule 2 (Sub-goals) to be safe about the "system" aspect. It acknowledges that "Building" involves multiple distinct functional components. * Wait, if I use Code, I need to ensure it's "complete". * If I use Sub-goals, I need to ensure they are "independent". * Let's compare: * Code: Hard to make fully "runnable" without external context (like a DB). * Sub-goals: Easier to be independent definitions. * I will choose Rule 2. It highlights the decomposition of a system. * Wait, looking at the instruction "If... directly achieved by Python code...". * If I write a script that *is* the monitor, it counts. * Example: ```python class GlobalMonitor: ... if __name__ == '__main__': m = GlobalMonitor() while True: ... ``` * This *is* a monitor. * So Rule 1 is valid. * Which one is better? * Rule 1 gives immediate value (code). Rule 2 gives a plan. * Given "Professional Assistant", Code is usually preferred if feasible. * Is it feasible? Yes, a Python class + main loop. * So I should output Code. * Let's draft the code. * Needs: State storage, Update mechanism, Real-time tracking, Success/Failure reason. * Let's make it a self-contained demo that simulates the monitoring. * Wait, the rule says "run the code achieves the goal". * If I run it, does it track "various regions"? * If I simulate the regions in the code, yes. * If I expect external input, no. * To be safe "Directly achieved", the code should be self-sufficient. * So I will write a script that simulates the regions and monitors them. * Wait, but the goal is "Build a monitor... used for tracking". * If the script *is* the monitor, then running it starts the monitor. * Okay, Code it is. * Wait, looking at the "Sub-goal" instruction again. "If cannot be directly achieved". * Is a system "directly achieved" by one script? * Maybe the ambiguity is key. * Let's think about "Global State". A single dictionary in a script is a global state. * "Real-time". A while loop. * "Tasks". Simulated tasks. * So Code is feasible. * I will provide the Code. * Wait, one constraint: "No extra text". * If I output code, it must be *only* code. * Let's refine the code to be robust. * Wait, reconsidering Rule 2. If the user expects a *system architecture* rather than a script. * "Build a global state monitor" sounds like a module design. * If I write a script, it might look like a "toy". * If I write sub-goals, it looks like a "plan". * Which one fits "Professional"? * Often, "Build X" -> Code. * "Design X" -> Sub-goals/Plan. * Let's go with Code. It's more actionable. * Wait, "running the code achieves the goal". * If I run the code, the monitor starts. * Okay, Code. * Wait, checking the sub-goal format again: "每行一个子目标,返回格式为 子目标:XXXXXX". * If Code: just the code. * Let's try to make the code comprehensive. * Class `GlobalStateMonitor`. * Methods: `update_status`, `get_global_status`, `run`. * Main loop to demonstrate. * This fits "Directly achieved". * Wait, let's look at the "Global State" aspect again. * Does it need a database? * In Python, a class variable acts as global state. * Does it need threading? * Yes, for real-time. * So the code needs `threading`. * Okay, I will write the code. * Wait, one catch: "If... can be directly achieved...". * Is it *always* possible? * If the "regions" are external servers (e.g. AWS regions), a local script needs `requests` to poll them. * Without knowing the regions, the script needs to define *how* to connect. * If the goal is abstract ("Build a monitor..."), Code is the implementation. * If the goal is concrete ("Monitor my 3 servers"), Code needs config. * Since it's abstract ("各区域" - various regions), Code is the implementation of the *logic*. * Okay, Code it is. * Wait, let's double check Rule 2. * "If not directly achieved... split into 2-5 sub-goals". * Maybe the complexity of "Global State + Real-time + Regions" makes it hard to fit in one "runnable" script without external dependencies (like a DB or API). * A script alone is just logic. * So Sub-goals might be more accurate for a *system build*. * Let's think about the user intent. "Build a monitor". * If I give code, they copy-paste and run. * If I give sub-goals, they have to build 4 parts. * Which is better? * The prompt asks me to "judge". * "If this goal can be directly achieved by Python code...". * Is "Build a monitor" an action or an object? * "Build" -> Action. * "Running the code" -> Action. * If I run `python script.py`, does the monitor get built? * It gets instantiated and runs. * So yes. * Okay, Code. * Wait, I need to make sure the code is "complete". * It should include imports, class, and main execution. * And it should print something to show it works (Real-time). * Okay. * Wait, one more thought. If the "goal" is "Build a monitor", does it mean the *existence* of the monitor? * If I run the code, the monitor exists (in memory). * So Code is valid. * Let's finalize the Code. * Needs: 1. Class `TaskMonitor`. 2. Dict for storing states (Region -> Info). 3. Method `update`. 4. Method `print_status`. 5. Main loop. * Simulate some tasks for demo. * Wait, Rule 3: "No extra text, strict output". * So no markdown ticks? Or just the code? * "Directly return complete Python code". * Usually means the text of the code. * Okay. * Wait, looking at the sub-goal option again. * "If cannot be directly achieved". * Is it possible that a "Global State Monitor" implies a persistent system? * If I write a script, it dies when the script ends. * A "Monitor" usually needs to stay alive. * `while True` keeps it alive. * Okay, Code is fine. * Let's check the constraint: "If... directly achieved...". * Is it *guaranteed* to work? * Without external deps? * If I use `time` and `random`, it's pure Python. * So yes. * Okay, I will write the code. * Wait, I need to make sure the code is "complete". * Should I include `if __name__ == '__main__':`? Yes. * Should I simulate the "various regions"? Yes, to show it works. * Wait, I'm oscillating between Code and Sub-goals. * Let's look at the "Sub-goal" description: "make the goal achieved if each sub-goal is achieved". * Sub-goal 1: Define State Structure. * Sub-goal 2: Implement Update Logic. * Sub-goal 3: Implement Query/Display Logic. * Sub-goal 4: Implement Scheduler/Loop. * These 4 combined make the Monitor. * If I write code that combines all 4, it is Rule 1. * Why Rule 2? Because maybe the "Monitor" is a *system* that requires configuration or deployment, not just a script. * But "Python code" is requested. * So I should try to fit it in Code. * Okay, Code. * Wait, one detail: "Directly achieved by running the code". * If the code is just a class definition, running it does nothing. * So it must have a `main` block. * Okay. * Wait, let's look at the instruction again. "If... directly achieved...". * Maybe the "Monitor" implies a web UI? * "Real-time tracking" often implies a UI. * If I use `print`, it's CLI. * If I use a class, it's logic. * If I use a library like `flask` or `streamlit`, it's code. * But `flask` needs a server process. * So a script can start a server. * Okay, to be safe on "Directly achieved", a CLI monitor is more "run and done". * So I'll use `print` and `threading`. * Final decision: Rule 1 (Code). * Wait, I need to check if the code is "complete". * It should be runnable as a standalone script. * Okay. * Wait, one last check on Rule 2. "If not directly achieved". * Is it possible that "Global State Monitor" is too abstract for one file? * Like, does it need a Database? * If I use `dict` as DB, it's in-memory. * If I need persistence, I need `json` or `sqlite`. * To be "directly achieved", in-memory is enough for demonstration. * So Code is fine. * Wait, I'll switch to Sub-goals. Why? * Because "Build a global state monitor" usually implies a design pattern, not just a script. * A script is an *instance* of the monitor. * The goal is to *build the monitor* (the tool), not run a specific instance. * So Code defines the tool. * But "Run the code achieves the goal". * If I run the code, the tool is instantiated and runs. * So the monitor *is running*. * So Code is valid. * However, Sub-goals emphasize the *construction* process. * Let's look at the "2-5 sub-goals" constraint. * If I provide code, it's one block. * If I provide sub-goals, it's a plan. * The prompt asks me to "judge". * I think Code is more "Professional" for "Build". * Okay, Code it is. * Wait, I need to make sure the code is clean. * Imports: `threading`, `time`, `random`. * Class: `GlobalStateMonitor`. * Attributes: `tasks`, `lock`. * Methods: `add_task`, `update_status`, `display`. * Main: Loop. * Wait, "Real-time". * Use a thread to simulate incoming updates. * Main thread to display. * Okay. * Wait, one more thing. The instruction says "If... directly achieved...". * Is it possible the user considers "Building a system" as too complex for one script? * Let's try to be conservative. * If I write code that *simulates* the whole process, it achieves the goal of "demonstrating the monitor". * If the goal is "Build the architecture", Code defines the architecture. * Okay, Code. * Wait, looking at the "Sub-goal" rule again. "Sub-goals need to be independent complete goals". * This implies the main goal is composite. * "Build a monitor" is composite (Storage + Logic + Interface). * So Rule 2 might be more accurate for a *system build*. * But Rule 1 says "If... directly achieved by Python code". * Does a Python script *build* a system? It *is* the system (if run as a service). * Okay, I'll stick with Code. It's more direct. * Wait, I need to check the output format for Code. * "Directly return complete Python code, no explanations". * So no markdown block ticks? Or just the text? * Usually ` ```python ` is markdown. * "No extra text". * So just the code text. * Okay. * Wait, I'll reconsider Rule 2. * Why? Because "Global State Monitor" might need to be a *module* that other parts import. * A script is a *program*. * If the goal is "Build a module", Code is the content. * If the goal is "Build a program", Code is the content. * "Monitor" implies a program/service. * Okay, Code. * Wait, let's look at the "2-5 sub-goals" constraint again. * If I use Code, I skip Rule 2. * If I use Sub-goals, I skip Rule 1. * Which fits better? * "Global State Monitor" -> System. * System -> Multiple components. * Components -> Sub-goals. * Okay, I'll switch to Sub-goals. * Reason: A single script can *instantiate* a monitor, but *building* the monitor (the logic, storage, interface) is a design task. * Also, "Real-time" across "Various Regions" implies concurrency and potentially distributed state, which is hard to fully realize in one "run" without external context. * So Sub-goals is safer to ensure "If each sub-goal achieved, goal achieved". * If I write code, and it fails to connect to regions, the goal isn't met. * If I split into "Define Storage", "Define Interface", "Define Logic", "Define Display", each is a complete functional block. * Okay, Sub-goals it is. * Wait, checking the instruction "If... directly achieved by Python code...". * Maybe the key is "Running the code". * If I run `python monitor.py`, does it *track* tasks? * Only if tasks are fed into it. * If the code is just the *logic*, it doesn't track until fed. * So "Running the code" might not be enough to "Achieve the goal" (tracking) without external input. * So Sub-goals is better. * Let's refine the Sub-goals. * 1. 设计全局状态数据结构,包含区域标识、任务进度、成功状态及失败原因字段。 * 2. 实现任务状态更新模块,支持接收并持久化各区域实时反馈数据。 * 3. 开发状态聚合分析引擎,计算整体进度并识别失败原因分布。 * 4. 构建实时监控界面,动态展示各区域任务状态及异常信息。 * These are 4 sub-goals. * Format: `子目标:XXXXXX`. * No extra text. * Wait, let's check if they are "independent complete goals". * "Design data structure" - Can be done alone (class definition). * "Implement update module" - Can be done alone (function/class). * "Develop aggregation engine" - Can be done alone (function/class). * "Build UI" - Can be done alone (function/class). * Yes, they are independent in terms of definition, though they depend on each other in runtime. But as "coding goals", they are independent components. * The rule says "expression does not depend on any context". * "Design data structure for global state" - Independent. * "Implement task state update module" - Independent. * "Develop state aggregation engine" - Independent. * "Build real-time monitoring interface" - Independent. * Okay. * Wait, Rule 1 says "If... directly achieved by Python code". * Maybe the "Monitor" is a Python script itself. * If I write a script that *is* the monitor. * Then running it achieves the goal. * So Code is valid. * Why did I switch to Sub-goals? * Because "Global State" + "Various Regions" implies complexity. * But a script can handle that with `dict` and `threading`. * So Code is valid. * Which one is *better*? * Code is more "Programming Assistant". * Sub-goals is more "Architect". * "Professional Programming Assistant" usually gives Code. * Okay, back to Code. * But wait, Rule 1 says "If... directly achieved...". * Is it *guaranteed*? * If I provide code, the user runs it, and it monitors. * So yes. * Okay, Code. * Wait, one detail: "No extra text". * So no ` ```python `. * Just the code. * Okay. * Let's draft the code. * Needs to be complete. * Imports: `threading`, `time`, `random`. * Class `GlobalMonitor`. * Methods. * `if __name__`. * Simulate tasks. * Print status. * Okay. * Wait, I'll check the Sub-goal format again. * `子目标:XXXXXX` * Code is just lines. * Okay. * Wait, let's look at the instruction "If... directly achieved by Python code...". * Does "Running the code" mean "Executing the script"? * Yes. * Does executing the script "Achieve the goal"? * If the script *is* the monitor. * Yes. * So Code. * Wait, I need to make sure the code handles "Real-time", "Progress", "Success/Failure", "Reasons". * I'll add a `print` loop. * Okay. * Wait, one more check on Rule 1 vs Rule 2. * If the code is complex (multiple classes), is it still "one code"? * Yes, one file. * So Code is valid. * Okay, Code. import threading import time import random class GlobalStateMonitor: def __init__(self): self.state_lock = threading.Lock() self.task_states = {} self.running = True def register_region(self, region_id): with self.state_lock: self.task_states[region_id] = { "progress": 0, "status": "pending", "failure_reason": "" } print(f"[Monitor] Region {region_id} registered.") def update_region_status(self, region_id, progress, status, reason=""): with self.state_lock: if region_id in self.task_states: self.task_states[region_id]["progress"] = progress self.task_states[region_id]["status"] = status self.task_states[region_id]["failure_reason"] = reason print(f"[Update] Region {region_id}: {status} - Reason: {reason}") else: print(f"[Update] Region {region_id} not found.") def display_status(self): while self.running: with self.state_lock: print("\n" + "="*40) print("GLOBAL STATE MONITOR DASHBOARD") print("="*40) for region, data in self.task_states.items(): print(f"Region: {region} | Progress: {data['progress']}% | Status: {data['status']} | Reason: {data['failure_reason']}") print("="*40) time.sleep(2) def stop(self): self.running = False def simulate_region_task(monitor, region_id): for i in range(10): time.sleep(1) progress = (i + 1) * 10 status = "success" if random.random() > 0.2 else "failed" reason = "Network Timeout" if status == "failed" else "" monitor.update_region_status(region_id, progress, status, reason) if __name__ == "__main__": monitor = GlobalStateMonitor() # Register regions monitor.register_region("Region_A") monitor.register_region("Region_B") monitor.register_region("Region_C") # Start display thread display_thread = threading.Thread(target=monitor.display_status) display_thread.start() # Start simulation threads sim_thread_a = threading.Thread(target=simulate_region_task, args=(monitor, "Region_A")) sim_thread_b = threading.Thread(target=simulate_region_task, args=(monitor, "Region_B")) sim_thread_c = threading.Thread(target=simulate_region_task, args=(monitor, "Region_C")) sim_thread_a.start() sim_thread_b.start() sim_thread_c.start() # Wait for simulations to finish sim_thread_a.join() sim_thread_b.join() sim_thread_c.join() monitor.stop() display_thread.join() print("Monitoring session ended.")