状态:已完成
【Python 代码】实现主程序入口,整合HTTP与TCP检测逻辑并处理异常与日志输出
Thinking Process:
1. **Analyze the Request:**
* Role: Professional Programming Assistant.
* Task: Judge and answer based on strict requirements.
* Goal: Implement main program entry, integrate HTTP and TCP detection logic, handle exceptions and log output.
* Rules:
1. If the goal can be directly implemented in Python (running the code achieves the goal), return the complete Python code only, no explanations.
2. If it cannot be directly implemented, split the goal into 2-5 independent sub-goals. Each sub-goal must be complete and context-independent. Format: "子目标:XXXXXX" per line.
3. No extra text, strict output format.
2. **Evaluate the Goal:**
* Goal: "Implement main program entry, integrate HTTP and TCP detection logic, handle exceptions and log output".
* Language: Python (implied by Rule 1).
* Feasibility: Can this be done in a single Python script?
* Yes. A Python script can have a `if __name__ == "__main__":` block (main entry).
* It can define functions or classes for HTTP detection and TCP detection.
* It can integrate them (e.g., call them sequentially or concurrently).
* It can use the `logging` module for log output.
* It can use `try-except` blocks for exception handling.
* Constraint Check: The prompt asks to judge *if* it can be directly implemented. Usually, a "main program entry" implies a runnable script. A single script file containing the logic, entry point, integration, exception handling, and logging setup is sufficient to "achieve the goal" upon running (assuming necessary parameters like hosts are provided or hardcoded for demonstration).
* Decision: It *can* be directly implemented in Python code. A single script satisfies the requirement of "running the code achieves the goal".
3. **Draft the Code:**
* Need `logging` setup.
* Need `requests` for HTTP (or `urllib`).
* Need `socket` for TCP.
* Need `try-except` for error handling.
* Need `main` entry point.
* Keep it concise but functional.
* *Self-Correction on Rule 1:* "If this goal can be directly implemented in Python code, that is, running the code can achieve the goal, directly return complete Python code".
* Does "achieving the goal" mean the code runs without error and performs the tasks? Yes.
* Should I include imports? Yes.
* Should I include sample logic? Yes.
* Is it too complex? A single file is fine.
4. **Drafting the Content:**
```python
import logging
import socket
import requests
from typing import List
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def check_http(host: str, port: int = 80) -> bool:
try:
logger.info(f"Checking HTTP on {host}:{port}")
response = requests.get(f"http://{host}:{port}", timeout=5)
return response.status_code == 200
except Exception as e:
logger.error(f"HTTP check failed: {e}")
return False
def check_tcp(host: str, port: int) -> bool:
try:
logger.info(f"Checking TCP on {host}:{port}")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
result = sock.connect_ex((host, port))
sock.close()
return result == 0
except Exception as e:
logger.error(f"TCP check failed: {e}")
return False
def main():
try:
targets = [
{"host": "www.google.com", "port": 80, "type": "http"},
{"host": "127.0.0.1", "port": 22, "type": "tcp"}
]
for target in targets:
if target["type"] == "http":
check_http(target["host"], target["port"])
elif target["type"] == "tcp":
check_tcp(target["host"], target["port"])
except Exception as e:
logger.critical(f"Main execution error: {e}")
if __name__ == "__main__":
main()
```
5. **Review against Rules:**
* Rule 1: If directly implementable, return code only.
* Rule 2: If not, split into sub-goals.
* Rule 3: No extra text.
* Is it directly implementable? Yes. A single `.py` file does the job.
* Are there dependencies? `requests` might need installation, but logically the code *implements* the goal. Usually, in these contexts, `requests` is acceptable as standard library `urllib` could be used to avoid external deps, but `requests` is more idiomatic for HTTP. Let's use `urllib` to make it more standalone without `pip install`, ensuring "running the code" implies minimal setup. Or keep `requests` as it's standard for "HTTP detection". Let's stick to `requests` as it's cleaner, but maybe `urllib` is safer for "directly run". However, the prompt implies "Python code", usually allowing standard libs or common libs. To be safe on "directly implemented" (meaning logic-wise), `requests` is fine.
* Wait, strictly speaking, `requests` isn't installed by default. `urllib` is. To ensure "running the code" works out of the box without `pip`, `urllib` and `socket` are better.
* Let's adjust to use `urllib.request` for HTTP to ensure it's truly "directly implementable" without external dependencies.
* Refined Code:
```python
import logging
import socket
import urllib.request
import urllib.error
import sys
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def detect_http(host: str, port: int = 80) -> bool:
try:
logger.info(f"HTTP Check: {host}:{port}")
url = f"http://{host}:{port}"
urllib.request.urlopen(url, timeout=5)
return True
except urllib.error.URLError as e:
logger.error(f"HTTP Error: {e}")
return False
except Exception as e:
logger.error(f"HTTP Unknown: {e}")
return False
def detect_tcp(host: str, port: int) -> bool:
try:
logger.info(f"TCP Check: {host}:{port}")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
result = sock.connect_ex((host, port))
sock.close()
return result == 0
except Exception as e:
logger.error(f"TCP Error: {e}")
return False
def main():
try:
logger.info("Starting detection...")
hosts = [
("www.example.com", 80, "http"),
("127.0.0.1", 22, "tcp")
]
for host, port, protocol in hosts:
if protocol == "http":
detect_http(host, port)
elif protocol == "tcp":
detect_tcp(host, port)
logger.info("Detection completed.")
except Exception as e:
logger.critical(f"Main Exception: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
```
This looks solid. It integrates HTTP and TCP, has main entry, exception handling, and logging.
6. **Final Check:**
* Output format: Just the code.
* Language: Python.
* No explanations.
7. **Decision:** Since a single script suffices, Rule 1 applies.
Wait, re-reading Rule 1: "If this goal can be directly implemented in Python code, that is, running the code can achieve the goal, directly return complete Python code, no explanations."
Does "running the code" imply it finishes successfully? Yes.
Does it imply external dependencies? Usually, yes, but `urllib` is builtin.
So Rule 1 is the correct choice.
Wait, let's look at Rule 2 again: "If it cannot be directly implemented...".
Is there ambiguity? Sometimes "Main program entry" implies a structure where submodules exist. But a single file *is* a main program entry.
I will proceed with Rule 1.
One more check: "子目标需要是独立完整的目标,表述中不依赖任何上下文" (Sub-goals need to be independent complete goals, not relying on context). This applies to Rule 2.
Since I choose Rule 1, I just output code.
Wait, is there a nuance? "整合 HTTP 与 TCP 检测逻辑" (Integrate HTTP and TCP detection logic).
If I write a script that has both functions and calls them in main, it is integrated.
"处理异常与日志输出" (Handle exceptions and log output).
`try-except` and `logging` module cover this.
"实现主程序入口" (Implement main program entry).
`if __name__ == "__main__":` covers this.
So Rule 1 is valid.
Wait, one detail: "直接返回完整 Python 代码" (Directly return complete Python code).
I should ensure no markdown code block fences (```python ... ```)?
Usually, "return code" implies the text content. But often in LLM interfaces, markdown blocks are expected for code.
The rule says "不要任何解释" (no explanations). It doesn't explicitly ban markdown blocks, but "directly return complete Python code" might mean raw text.
However, to be safe and clean, I will use markdown code blocks as it's standard for "Python code" representation in chat, unless strictly raw text is demanded.
Looking at "不要多余文字" (no extra text). Markdown fences ` ``` ` could be considered extra text or formatting.
But usually, when asked for code, ` ```python ` is standard.
Let's look at the instruction: "直接返回完整 Python 代码".
If I write:
```python
code
```
Is that "extra text"?
To be strictly compliant with "no extra text", I might omit the fences. But without fences, it's hard to distinguish from text.
However, Rule 3 says "No extra text".
Let's assume the code block syntax is part of the code representation, not explanation.
But to be safest on "no extra text", I will output the code directly.
Actually, most prompts like this expect markdown. Let's look at similar tasks. Usually, ` ```python ` is accepted.
But strict adherence might mean raw text.
Let's check the instruction again: "直接返回完整 Python 代码".
I'll include the markdown fence because it's the standard way to denote code in this interface, but I won't add titles like "Here is the code".
Wait, if I put ` ```python ` it counts as characters.
Let's stick to the standard markdown block for clarity, as "code" usually implies that format in chat.
Actually, looking at the strictness "严格按要求输出", I will output the code block.
Wait, I need to decide between Rule 1 and Rule 2.
Is it possible that the goal requires a file structure (e.g. separate modules)?
"整合...逻辑" (Integrate logic). A single file integrates logic.
So Rule 1 is definitely the intended path for a "main program entry".
If the goal was "Design a microservice architecture", Rule 2 would be better.
"Implement main program entry" -> Script.
Okay, final check on code content.
1. Logging setup.
2. HTTP function (urllib).
3. TCP function (socket).
4. Main function with try-except.
5. Entry point.
Ready.
Wait, one more thought: Rule 1 says "If this goal can be directly implemented... return complete Python code".
Rule 2 says "If not... split into 2-5 sub-goals".
Is there any reason a single file isn't "complete"?
Sometimes "Integration" implies separate modules. But "Main program entry" usually means the `__main__` block.
I think Rule 1 is the strongest fit.
Let's refine the code to be robust.
Code:
```python
import logging
import socket
import urllib.request
import urllib.error
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
def check_http(host: str, port: int = 80) -> bool:
try:
logger.info(f"HTTP Check: {host}:{port}")
url = f"http://{host}:{port}"
with urllib.request.urlopen(url, timeout=5) as resp:
logger.info(f"HTTP Status: {resp.status}")
return True
except Exception as e:
logger.error(f"HTTP Check Failed: {e}")
return False
def check_tcp(host: str, port: int) -> bool:
try:
logger.info(f"TCP Check: {host}:{port}")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
result = sock.connect_ex((host, port))
sock.close()
if result == 0:
logger.info(f"TCP Port {port} Open")
else:
logger.info(f"TCP Port {port} Closed")
return result == 0
except Exception as e:
logger.error(f"TCP Check Failed: {e}")
return False
def main():
try:
targets = [
("www.google.com", 80, "http"),
("127.0.0.1", 22, "tcp")
]
logger.info("Starting Detection Program")
for host, port, protocol in targets:
if protocol == "http":
check_http(host, port)
elif protocol == "tcp":
check_tcp(host, port)
logger.info("Detection Program Finished")
except Exception as e:
logger.critical(f"Main Program Exception: {e}")
if __name__ == "__main__":
main()
```
This looks complete.
Wait, checking Rule 3: "不要添加多余文字" (Don't add extra text).
Does ` ```python ` count?
If I write raw text, it might look like a paragraph.
I will use the markdown block as it's standard for "Code".
But to be super strict, maybe just the text.
Let's assume markdown block is expected for "Python Code".
Wait, I should check if the prompt implies the code needs to be *runnable* immediately. `urllib` is built-in, so yes.
Okay, proceeding.
Wait, one detail in Rule 1: "直接返回完整 Python 代码,不要任何解释".
If I add ` ```python ` and ` ``` `, is it explanation?
Usually, it's formatting.
I will include them for clarity.
Wait, looking at the instruction "每行一个子目标" (One sub-goal per line) in Rule 2.
Rule 1 says "直接返回完整 Python 代码".
So if Rule 1 applies, no "子目标:" prefix.
Final check on logic:
- Main entry: `if __name__ == "__main__": main()`
- HTTP logic: `check_http` using `urllib`
- TCP logic: `check_tcp` using `socket`
- Integration: `main` calls both based on config.
- Exceptions: `try-except` blocks in functions and main.
- Logging: `logging` module configured.
Looks good.
Wait, is there a chance Rule 2 is better?
If the system expects "Sub-goals" for a complex architectural task.
But "Main program entry" suggests a single file.
If I choose Rule 2, I'd output:
子目标:设计 HTTP 检测函数
子目标:设计 TCP 检测函数
子目标:配置日志系统
子目标:实现主函数入口
子目标:集成异常处理机制
But Rule 1 says "If ... running code achieves goal".
A single file achieves the goal.
So Rule 1 is preferred.
Let's produce the code.
One small adjustment: `urllib.request.urlopen` might raise `URLError` or `HTTPError`. Catching `Exception` covers both.
I will keep it simple.
Final check on "No extra text".
I will output:
```python
... code ...
```
Without any intro sentence like "Here is the code".
Wait, should I remove the markdown fences to be strictly "no extra text"?
"直接返回完整 Python 代码" -> "Directly return complete Python code".
If I return:
import logging
...
It is code.
If I return:
```python
import logging
...
```
The fences are formatting.
In many strict prompts, fences are ignored.
I'll include them for better readability as it's a "Programming Assistant".
Wait, I'll remove the `typing` import to keep it minimal and avoid version issues if not needed, though `typing` is standard. I used `-> bool` which is valid in Python 3.
I'll keep `typing` out to be minimal.
Wait, one more thing. `urllib` in Python 2 vs 3. `urllib.request` is Py3. `urllib2` is Py2.
Assuming Python 3 is standard now.
I'll use `urllib.request`.
Okay, ready to generate.
Wait, I need to make sure I don't add "子目标:" if Rule 1 is chosen.
Yes.
Wait, re-reading Rule 1: "如果这个目标可以直接用 Python 代码实现... 请直接返回完整 Python 代码".
Re-reading Rule 2: "如果不能直接实现... 返回格式为 子目标:XXXXXX".
So if Rule 1, no "子目标:" prefix.
Okay.
Wait, one last check. Is there any reason `requests` is needed for "HTTP"? `urllib` is a bit verbose.
But `requests` needs `pip`. `urllib` is stdlib. "Running the code" implies less setup. `urllib` is safer for "directly".
Okay.
Code structure:
1. Imports.
2. Logger config.
3. Http func.
4. Tcp func.
5. Main func.
6. Entry.
Let's write it.
```python
import logging
import socket
import urllib.request
import urllib.error
# 配置日志输出
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
def check_http(host: str, port: int = 80) -> bool:
"""执行 HTTP 协议检测"""
try:
logger.info(f"Starting HTTP check on {host}:{port}")
url = f"http://{host}:{port}"
with urllib.request.urlopen(url, timeout=5) as response:
logger.info(f"HTTP check success, status: {response.status}")
return True
except urllib.error.URLError as e:
logger.error(f"HTTP check failed: {e.reason}")
return False
except Exception as e:
logger.error(f"HTTP check exception: {e}")
return False
def check_tcp(host: str, port: int) -> bool:
"""执行 TCP 协议检测"""
try:
logger.info(f"Starting TCP check on {host}:{port}")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
result = sock.connect_ex((host, port))
sock.close()
if result == 0:
logger.info(f"TCP check success on port {port}")
else:
logger.warning(f"TCP check failed on port {port}")
return result == 0
except Exception as e:
logger.error(f"TCP check exception: {e}")
return False
def main():
"""主程序入口,整合逻辑并处理异常"""
try:
logger.info("=== Main Program Started ===")
targets = [
{"host": "www.google.com", "port": 80, "type": "http"},
{"host": "www.baidu.com", "port": 443, "type": "http"},
{"host": "127.0.0.1", "port": 22, "type": "tcp"}
]
for target in targets:
host = target["host"]
port = target["port"]
ptype = target["type"]
if ptype == "http":
check_http(host, port)
elif ptype == "tcp":
check_tcp(host, port)
else:
logger.warning(f"Unknown protocol type: {ptype}")
logger.info("=== Main Program Finished ===")
except Exception as e:
logger.critical(f"Main program fatal error: {e}")
if __name__ == "__main__":
main()
```