php控制台脚本错误输出到php_errors.log

本文介绍如何配置PHP CLI环境,使错误信息能够正确输出到指定的日志文件。通过调整php.ini配置,设置log_errors和error_log参数,确保PHP控制台脚本的错误可以被记录。同时,解决因权限问题导致日志无法写入的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

php控制台脚本错误输出到php_errors.log

问题描述

今天学习php函数的时候,发现错误没有输出到php_errors.log,遂有此文。

解决过程

先检查php.ini文件,需要有一下配置

log_errors = On
error_log =/apps/logs/php_errors.log		# 可自定义的位置

需要找到php.ini文件位置(没有的话,在输出的配置文件的位置复制一个php.ini.default)

php --ini

由于只是cli程序,修改配置文件后不需要重启什么,直接生效。(如果是web程序,需要重启php-fpm;如果web程序使用的是Apache,就重启Apache)

在代码中直接向日志文件中写入错误信息来测试

error_log('test');

还是没写进去(连文件都没有生成),然后自己手动新建一个文件,并给与写权限

sudo touch /apps/logs/php_errors.log
sudo chmod 664 /apps/logs/php_errors.log

再次执行代码,日志写入成功。

可能原因 - 运行权限问题

请检查 运行PHP CLI的用户帐户是否有对php_errors.log的写入权限。

#! /bin/bash # This script is created by DQE Ghosty Liu 2020/08/10 # ### RW TEST PARAMETER ### PARTITION="sdb1" declare -i RW_count=1 declare -i RW_cycle=1 #(1 cycle = 128 MB) Check_Flag=1 #(1 = check disk scan result; 0 = not check disk scan result) Remove_Flag=1 #(1 = remove test file; 0 = not remove test file) ### PKTGEN TEST PARAMETER ### PAIRS="ens8f0-ens8f1-8 enp2s0f0-enp2s0f1-9 enp130s0f0-enp130s0f1-10 ens5f0-ens5f1-11 ens5f2-ens5f3-12" #(port-port-core) JUMBO=y declare -i TIME=30 ### STRESS TEST PARAMETER ### COMMAND="stress -c 4 -m 4 --vm-bytes 1024M -t 60" declare -i CYCLE=20 #(1 cycle = 3 seconds) ### PING TEST PARAMETER ### declare -i PING_COUNT=10 ### RTC WAKE PARAMETER ### declare -i delay=30 # <Decide the RTC wake up delay time here.> ### SPECIAL SCAN PARAMETER ### check_item="error" # <Add other check item for SPECIAL_SCAN here.> ########################################################################################################## function DD() { for k in $(seq $RW_count `expr $RW_cycle - 1`) do if [ ! -z "$k" ] then dd if=/dev/zero of=/$partition/$count.$k.tmp bs=32M count=4 conv=fsync &> /dev/null & fi done dd if=/dev/zero of=/$partition/$count.$RW_cycle.tmp bs=32M count=4 conv=fsync &> /dev/null } function RW_TEST() { if [ "$count" -gt "1" ] && [ "$Check_Flag" -eq "1" ] then echo -e "Check DISK SCAN reeult ..." if [ -z "`diff -q /Test/CYCLE_LOG/DISK_SCAN/1.log /Test/CYCLE_LOG/DISK_SCAN/$count.log`" ] then echo -e "Check Pass." else echo -e "Check failed. RW Test will be terminated." echo "COUNT=$count :" >> /Test/CYCLE_LOG/rw_test_fail.log echo -e "Check failed. RW Test had been skipped." >> /Test/CYCLE_LOG/rw_test_fail.log return 1 fi fi echo -e "Start Storage R/W Test ..." if [ ! -d "/Test/CYCLE_LOG/RW_TEST" ] then mkdir -p /Test/CYCLE_LOG/RW_TEST fi for partition in $PARTITION do if [ ! -d "/Test/CYCLE_LOG/RW_TEST/$partition" ] then mkdir -p /Test/CYCLE_LOG/RW_TEST/$partition fi if [ ! -z "`ls /dev/ | grep $partition`" ] || [ ! -d "/$partition" ] then mkdir -p /$partition if [ -z "`mount | grep $partition`" ] then mount /dev/$partition /$partition else if [ ! -z "`mount | grep $partition | grep /mnt/hdd`" ] then echo "Please make sure that Partition: $partition is not used by Testbed!" rm -rf /$partition rm -rf /Test/CYCLE_LOG/RW_TEST/$partition continue fi fi echo "COUNT : $count" >> /Test/CYCLE_LOG/RW_TEST/$partition/result.log (time -p DD) 2>> /Test/CYCLE_LOG/RW_TEST/$partition/result.log & sleep 1 fi done while [ 1 ] do buf=`ps -aux | grep -i "/dev/zero" | wc -l` if [ "$buf" -eq "1" ] then break fi sleep 1 done sync sleep 5 for partition in $PARTITION do if [ -d "/$partition" ] then if [ "$Remove_Flag" -eq "1" ] then rm -rf /$partition/* sync fi umount /$partition fi done if [ ! -z "`dmesg | grep -i ata | grep -i error`" ] then echo "COUNT=$count :" >> /Test/CYCLE_LOG/rw_test_fail.log dmesg | grep -i ata | grep -i error >> /Test/CYCLE_LOG/rw_test_fail.log fi } function PKTGEN_TEST() { echo -e "Start PKTGEN Test ..." if [ ! -d "/Test/CYCLE_LOG/PKTGEN_TEST" ] then mkdir -p /Test/CYCLE_LOG/PKTGEN_TEST fi if [ -z "`lsmod | grep pkt`" ] then echo "Please install pktgen driver first!!" exit 1 fi for pair in $PAIRS do PORT_A=`echo $pair | cut -d "-" -f 1` PORT_B=`echo $pair | cut -d "-" -f 2` CPU_NUM=`echo $pair | cut -d "-" -f 3` ifconfig $PORT_A up ifconfig $PORT_B up if [ "$count" -le "1" ] then echo $PORT_A >> /Test/CYCLE_LOG/ethernet_port.list echo $PORT_B >> /Test/CYCLE_LOG/ethernet_port.list fi echo "rem_device_all" > /proc/net/pktgen/kpktgend_$CPU_NUM echo "add_device $PORT_A" > /proc/net/pktgen/kpktgend_$CPU_NUM echo "add_device $PORT_B" > /proc/net/pktgen/kpktgend_$CPU_NUM echo "max_before_softirq 10000" > /proc/net/pktgen/kpktgend_$CPU_NUM if [ ! -f "/proc/net/pktgen/$PORT_A" ] || [ ! -f "/proc/net/pktgen/$PORT_B" ] then echo "Fail to add $pair to pktgen" exit 1 fi echo "count 0" > /proc/net/pktgen/$PORT_A echo "count 0" > /proc/net/pktgen/$PORT_B if [ "$JUMBO" == "y" ] then ifconfig $PORT_A mtu 9000 up ifconfig $PORT_B mtu 9000 up echo "pkt_size 9014" > /proc/net/pktgen/$PORT_A echo "pkt_size 9014" > /proc/net/pktgen/$PORT_B else echo "pkt_size 1514" > /proc/net/pktgen/$PORT_A echo "pkt_size 1514" > /proc/net/pktgen/$PORT_B fi echo "delay 100" > /proc/net/pktgen/$PORT_A echo "delay 100" > /proc/net/pktgen/$PORT_B echo "dst_mac `ifconfig $PORT_B | grep ether | tr -s " " | cut -d " " -f 3`" > /proc/net/pktgen/$PORT_A echo "dst_mac `ifconfig $PORT_A | grep ether | tr -s " " | cut -d " " -f 3`" > /proc/net/pktgen/$PORT_B done sleep 10 echo start > /proc/net/pktgen/pgctrl & declare -i buf=`cat /sys/class/rtc/rtc0/since_epoch` buf=$buf+$TIME while [ 1 ] do if [ "`cat /sys/class/rtc/rtc0/since_epoch`" -le "$buf" ] then sleep 1 else break fi done kill -9 $! sleep 1 for i in `cat /Test/CYCLE_LOG/ethernet_port.list` do if [ ! -f "/Test/CYCLE_LOG/PKTGEN_TEST/$i" ] then mkdir -p /Test/CYCLE_LOG/PKTGEN_TEST/$i fi ethtool -S $i | grep -i crc > /Test/CYCLE_LOG/PKTGEN_TEST/$i/CRC_$count.log cat /proc/net/pktgen/$i > /Test/CYCLE_LOG/PKTGEN_TEST/$i/PKTGEN_$count.log for j in `cat /Test/CYCLE_LOG/PKTGEN_TEST/$i/CRC_$count.log` do declare -i buf=`echo $j | cut -d ":" -f 2 | cut -d " " -f 2` if [ "$buf" -gt "0" ] then echo "COUNT=$count :" >> /Test/CYCLE_LOG/pktgen_test_fail.log echo "$i pktgen test result has CRC errors." >> /Test/CYCLE_LOG/pktgen_test_fail.log fi done sync done } function TIME_STAMP() { if [ "$count" -eq "1" ] then cat /sys/class/rtc/rtc0/since_epoch > /Test/CYCLE_LOG/time_stamp_tmp.log echo "$count: 0" > /Test/CYCLE_LOG/time_stamp.log else declare -i Ntime=`cat /sys/class/rtc/rtc0/since_epoch` declare -i Otime=`cat /Test/CYCLE_LOG/time_stamp_tmp.log` echo "$count: `expr $Ntime - $Otime`" >> /Test/CYCLE_LOG/time_stamp.log echo $Ntime > /Test/CYCLE_LOG/time_stamp_tmp.log fi } function STRESS() { echo -e "Start Stress Test ..." sleep 3 $COMMAND & top -d 3 -n $CYCLE clear } function DMESG() { if [ ! -d "/Test/CYCLE_LOG/DMESG" ] then mkdir -p /Test/CYCLE_LOG/DMESG fi dmesg > /Test/CYCLE_LOG/DMESG/$count.log sync } function PING_TEST() { echo -e "Start PING Test ..." if [ ! -d "/Test/CYCLE_LOG/PING_TEST" ] then mkdir -p /Test/CYCLE_LOG/PING_TEST fi if [ ! -f "/Test/ping.config" ] then echo "Couldn't find ping.config on path /Test! Stop PING_TEST..." sleep 3 break else Ping_item=`cat /Test/ping.config` # <The ping.config shall be "name1_source-address1_destination-address1 name2_source-address2_destination-address2 ...".> for i in $Ping_item do ETH_NAME=`echo $i | cut -d "_" -f 1` S_ADDRESS=`echo $i | cut -d "_" -f 2` D_ADDRESS=`echo $i | cut -d "_" -f 3` ifconfig $ETH_NAME $S_ADDRESS up sleep 3 echo -e "\n$ETH_NAME ping $D_ADDRESS test..." ping -I $ETH_NAME $D_ADDRESS -c $PING_COUNT >> /Test/ping.$ETH_NAME.[$D_ADDRESS].tmp & done fi while [ 1 ] do Buf=`ps | grep -i eth | wc -l` if [ "$Buf" = "1" ] then sleep 3 break fi done Buf_stress=`ps | grep -i stress | wc -l` if [ "$Buf_stress" -ne "1" ] then pkill stress fi Ping_tmp=`ls /Test | grep -i .tmp` for i in $Ping_tmp do if [ ! -f "/Test/CYCLE_LOG/PING_TEST/$i" ] then mkdir -p /Test/CYCLE_LOG/PING_TEST/$i fi j=`echo $i | cut -d "." -f 2` cat /Test/$i >> /Test/CYCLE_LOG/PING_TEST/$i/$count.log if [ -z "`cat /Test/$i | grep -i ttl=`" ] then echo "COUNT=$count :" >> /Test/CYCLE_LOG/ping_test_fail.log echo "$i ping test failed." >> /Test/CYCLE_LOG/ping_test_fail.log cat /Test/$i >> /Test/CYCLE_LOG/ping_test_fail.log echo " " >> /Test/CYCLE_LOG/ping_test_fail.log ifconfig $j >> /Test/CYCLE_LOG/ping_test_fail.log echo " " >> /Test/CYCLE_LOG/ping_test_fail.log ethtool $j >> /Test/CYCLE_LOG/ping_test_fail.log echo "=====================================================" >> /Test/CYCLE_LOG/ping_test_fail.log fi rm -rf /Test/$i done sync sleep 1 } function SPECIAL_SCAN() { if [ ! -d "/Test/CYCLE_LOG/SPECIAL_SCAN" ] then mkdir -p /Test/CYCLE_LOG/SPECIAL_SCAN fi for i in `echo $check_item` do dmesg | grep -i $i | cut -d "]" -f 2 >> /Test/CYCLE_LOG/SPECIAL_SCAN/$count.log dmesg | grep -i $i >> /Test/CYCLE_LOG/special_scan.log done echo "=====================================================" >> /Test/CYCLE_LOG/special_scan.log if [ -f "/Test/CYCLE_LOG/SPECIAL_SCAN/1.log" ] then BUFFER=`diff -q /Test/CYCLE_LOG/SPECIAL_SCAN/1.log /Test/CYCLE_LOG/SPECIAL_SCAN/$count.log` if [ ! -z "$BUFFER" ] then echo "COUNT=$count :" >> /Test/CYCLE_LOG/SPECIAL_SCAN_fail.log diff /Test/CYCLE_LOG/SPECIAL_SCAN/1.log /Test/CYCLE_LOG/SPECIAL_SCAN/$count.log >> /Test/CYCLE_LOG/SPECIAL_SCAN_fail.log echo " " >> /Test/CYCLE_LOG/SPECIAL_SCAN_fail.log fi fi sync sleep 1 } function USB_SCAN() { echo -e "Scanning USB devices ..." if [ ! -d "/Test/CYCLE_LOG/USB_SCAN" ] then mkdir -p /Test/CYCLE_LOG/USB_SCAN fi lsusb -tvv >> /Test/CYCLE_LOG/USB_SCAN/$count.log lsusb -tvv >> /Test/CYCLE_LOG/usb_scan.log echo "=====================================================" >> /Test/CYCLE_LOG/usb_scan.log if [ -f "/Test/CYCLE_LOG/USB_SCAN/1.log" ] then BUFFER=`diff -q /Test/CYCLE_LOG/USB_SCAN/1.log /Test/CYCLE_LOG/USB_SCAN/$count.log` if [ ! -z "$BUFFER" ] then echo "COUNT=$count :" >> /Test/CYCLE_LOG/USB_SCAN_fail.log diff /Test/CYCLE_LOG/USB_SCAN/1.log /Test/CYCLE_LOG/USB_SCAN/$count.log >> /Test/CYCLE_LOG/USB_SCAN_fail.log echo " " >> /Test/CYCLE_LOG/USB_SCAN_fail.log fi fi #/Test/67b-usblist.sh >> /Test/CYCLE_LOG/tb_usblist.log sync sleep 1 } function DRIVER_INSTALL() { for i in /Test/*.ko do insmod $i done sleep 1 } function PCIE_SCAN() { echo -e "\nScanning PCIe devices ..." if [ ! -d "/Test/CYCLE_LOG/PCIE_SCAN" ] then mkdir -p /Test/CYCLE_LOG/PCIE_SCAN fi for i in `lspci | sed 's/ /_/g'` do DEVICE=`echo $i | cut -d "_" -f 1` LNK_CAP_SPEED=`lspci -s $DEVICE -vv | grep LnkCap: | cut -d ":" -f 2 | cut -d "," -f 2` LNK_CAP_WIDTH=`lspci -s $DEVICE -vv | grep LnkCap: | cut -d ":" -f 2 | cut -d "," -f 3` LNK_STA_SPEED=`lspci -s $DEVICE -vv | grep LnkSta: | cut -d ":" -f 2 | cut -d "," -f 1` LNK_STA_WIDTH=`lspci -s $DEVICE -vv | grep LnkSta: | cut -d ":" -f 2 | cut -d "," -f 2` if [ ! -z "$LNK_CAP_SPEED" ] && [ ! -z "$LNK_STA_SPEED" ] then echo "$i : CAPABILITY=$LNK_CAP_SPEED, $LNK_CAP_WIDTH & STATUS=$LNK_STA_SPEED, $LNK_STA_WIDTH" >> /Test/CYCLE_LOG/PCIE_SCAN/$count.log echo "$i : CAPABILITY=$LNK_CAP_SPEED, $LNK_CAP_WIDTH & STATUS=$LNK_STA_SPEED, $LNK_STA_WIDTH" >> /Test/CYCLE_LOG/pcie_scan.log else echo "$i :" >> /Test/CYCLE_LOG/PCIE_SCAN/$count.log echo "$i :" >> /Test/CYCLE_LOG/pcie_scan.log fi done echo "Total count = `lspci | wc -l`" >> /Test/CYCLE_LOG/PCIE_SCAN/$count.log echo "Total count = `lspci | wc -l`" >> /Test/CYCLE_LOG/pcie_scan.log echo "=====================================================" >> /Test/CYCLE_LOG/pcie_scan.log if [ -f "/Test/CYCLE_LOG/PCIE_SCAN/1.log" ] then BUFFER=`diff -q /Test/CYCLE_LOG/PCIE_SCAN/1.log /Test/CYCLE_LOG/PCIE_SCAN/$count.log` if [ ! -z "$BUFFER" ] then echo "COUNT=$count :" >> /Test/CYCLE_LOG/PCIE_SCAN_fail.log diff /Test/CYCLE_LOG/PCIE_SCAN/1.log /Test/CYCLE_LOG/PCIE_SCAN/$count.log >> /Test/CYCLE_LOG/PCIE_SCAN_fail.log echo " " >> /Test/CYCLE_LOG/PCIE_SCAN_fail.log fi fi #/Test/64a-get_pcilist.sh >> /Test/CYCLE_LOG/tb_pcilist.log sync sleep 1 } function DISK_SCAN() { echo -e "Scanning Storage devices ..." if [ ! -d "/Test/CYCLE_LOG/DISK_SCAN" ] then mkdir -p /Test/CYCLE_LOG/DISK_SCAN fi for i in `ls /sys/block/` do if [ -f "/sys/block/$i/device/model" ] then if [ ! -z "$(cat /sys/block/$i/device/model | grep -v Virtual)" ] then SIZE=$(expr `cat /sys/block/$i/size` \* 512) echo -e "$i : `cat /sys/block/$i/device/model`\t Size = $SIZE Byte" >> /Test/CYCLE_LOG/DISK_SCAN/$count.log echo -e "$i : `cat /sys/block/$i/device/model`\t Size = $SIZE Byte" >> /Test/CYCLE_LOG/disk_scan.log fi elif [ -f "/sys/block/$i/device/name" ] then SIZE=$(expr `cat /sys/block/$i/size` \* 512) echo -e "$i : `cat /sys/block/$i/device/name`\t Size = $SIZE Byte" >> /Test/CYCLE_LOG/DISK_SCAN/$count.log echo -e "$i : `cat /sys/block/$i/device/name`\t Size = $SIZE Byte" >> /Test/CYCLE_LOG/disk_scan.log fi done echo "=====================================================" >> /Test/CYCLE_LOG/disk_scan.log if [ -f "/Test/CYCLE_LOG/DISK_SCAN/1.log" ] then BUFFER=`diff -q /Test/CYCLE_LOG/DISK_SCAN/1.log /Test/CYCLE_LOG/DISK_SCAN/$count.log` if [ ! -z "$BUFFER" ] then echo "COUNT=$count :" >> /Test/CYCLE_LOG/DISK_SCAN_fail.log diff /Test/CYCLE_LOG/DISK_SCAN/1.log /Test/CYCLE_LOG/DISK_SCAN/$count.log >> /Test/CYCLE_LOG/DISK_SCAN_fail.log echo " " >> /Test/CYCLE_LOG/DISK_SCAN_fail.log fi fi #/Test/66a-get_hddlist.sh >> /Test/CYCLE_LOG/tb_hddlist.log sync sleep 1 } function MAC_SCAN() { echo -e "Scanning Ethernet port MAC address ..." if [ ! -d "/Test/CYCLE_LOG/MAC_SCAN" ] then mkdir -p /Test/CYCLE_LOG/MAC_SCAN fi for i in `ls /sys/class/net/` do if [ -d "/sys/class/net/$i/device" ] then echo -e "$i\t : `cat /sys/class/net/$i/address`" >> /Test/CYCLE_LOG/MAC_SCAN/$count.log echo -e "$i\t : `cat /sys/class/net/$i/address`" >> /Test/CYCLE_LOG/mac_scan.log fi done echo "=====================================================" >> /Test/CYCLE_LOG/mac_scan.log if [ -f "/Test/CYCLE_LOG/MAC_SCAN/1.log" ] then BUFFER=`diff -q /Test/CYCLE_LOG/MAC_SCAN/1.log /Test/CYCLE_LOG/MAC_SCAN/$count.log` if [ ! -z "$BUFFER" ] then echo "COUNT=$count :" >> /Test/CYCLE_LOG/MAC_SCAN_fail.log diff /Test/CYCLE_LOG/MAC_SCAN/1.log /Test/CYCLE_LOG/MAC_SCAN/$count.log >> /Test/CYCLE_LOG/MAC_SCAN_fail.log echo " " >> /Test/CYCLE_LOG/MAC_SCAN_fail.log fi fi sync sleep 1 } function CLEAR_LOG() { if [ -d "/Test/CYCLE_LOG" ] then DATE=`date | sed 's/ /_/g' | sed 's/:/_/g' | sed 's/__/_/g'` mkdir -p /Test/$DATE mv /Test/CYCLE_LOG/* /Test/$DATE sync rm -rf /Test/CYCLE_LOG fi } function DEBUG() { if [ "$1" = "disk" ] || [ "$1" = "DISK" ] then DISK_SCAN echo "-------------------------------------------" cat /Test/CYCLE_LOG/DISK_SCAN/1.log echo "-------------------------------------------" rm -rf /Test/CYCLE_LOG/* elif [ "$1" = "pcie" ] || [ "$1" = "PCIE" ] then PCIE_SCAN echo "-------------------------------------------" cat /Test/CYCLE_LOG/PCIE_SCAN/1.log echo "-------------------------------------------" rm -rf /Test/CYCLE_LOG/* elif [ "$1" = "usb" ] || [ "$1" = "USB" ] then USB_SCAN echo "-------------------------------------------" cat /Test/CYCLE_LOG/USB_SCAN/1.log echo "-------------------------------------------" rm -rf /Test/CYCLE_LOG/* elif [ "$1" = "special" ] || [ "$1" = "SPECIAL" ] then SPECIAL_SCAN echo "-------------------------------------------" cat /Test/CYCLE_LOG/SPECIAL_SCAN/1.log echo "-------------------------------------------" rm -rf /Test/CYCLE_LOG/* elif [ "$1" = "mac" ] || [ "$1" = "MAC" ] then MAC_SCAN echo "-------------------------------------------" cat /Test/CYCLE_LOG/MAC_SCAN/1.log echo "-------------------------------------------" rm -rf /Test/CYCLE_LOG/* elif [ "$1" = "rw" ] || [ "$1" = "RW" ] then RW_TEST echo "-------------------------------------------" for i in $PARTITION do if [ -d "/$i" ] then cat /Test/CYCLE_LOG/RW_TEST/$i/result.log else echo "Partition: $i could not be tested!" fi done echo "-------------------------------------------" rm -rf /Test/CYCLE_LOG/* elif [ "$1" = "ping" ] || [ "$1" = "PING" ] then Ping_item=`cat /Test/ping.config` PING_TEST Log_list=`ls /Test/CYCLE_LOG/PING_TEST` for i in $Log_list do echo "-------------------------------------------" cat /Test/CYCLE_LOG/PING_TEST/$i/1.log echo "-------------------------------------------" done rm -rf /Test/CYCLE_LOG/* elif [ "$1" = "stress" ] || [ "$1" = "STRESS" ] then STRESS elif [ "$1" = "pktgen" ] || [ "$1" = "PKTGEN" ] then PKTGEN_TEST for i in `cat /Test/CYCLE_LOG/ethernet_port.list` do echo "-------------------------------------------" cat /Test/CYCLE_LOG/PKTGEN_TEST/$i/CRC_1.log cat /Test/CYCLE_LOG/PKTGEN_TEST/$i/PKTGEN_1.log echo "-------------------------------------------" done rm -rf /Test/CYCLE_LOG/* elif [ "$1" = "clean" ] || [ "$1" = "CLEAN" ] then CLEAR_LOG else mkdir -p /Test/CYCLE_LOG echo $1 > /Test/CYCLE_LOG/goal.tmp echo $2 > /Test/CYCLE_LOG/power_cycle.tmp fi } function POWER_CYCLE() { COMMAND=`cat /Test/CYCLE_LOG/power_cycle.tmp` if [ $COMMAND == poweroff ] then echo 0 > /sys/class/rtc/rtc0/wakealarm echo `expr $(date +%s) + $delay` > /sys/class/rtc/rtc0/wakealarm $COMMAND else $COMMAND fi } if [ -z "$1" ] then if [ -f "/Test/CYCLE_LOG/goal.tmp" ] && [ -f "/Test/CYCLE_LOG/power_cycle.tmp" ] then #DRIVER_INSTALL declare -i goal=`cat /Test/CYCLE_LOG/goal.tmp` declare -i count if [ ! -d "/Test/CYCLE_LOG" ] then mkdir -p /Test/CYCLE_LOG fi if [ ! -f "/Test/CYCLE_LOG/count.log" ] then echo 1 > /Test/CYCLE_LOG/count.log echo 1 > /Test/CYCLE_LOG/first.tmp fi count=`cat /Test/CYCLE_LOG/count.log` if [ ! -f "/Test/CYCLE_LOG/FLAG01" ] && [ ! -f "/Test/CYCLE_LOG/first.tmp" ] then echo "The $count times test is not finished correctly!" >> /Test/CYCLE_LOG/Warnning.log count+=1 echo $count > /Test/CYCLE_LOG/count.log else if [ -f "/Test/CYCLE_LOG/FLAG01" ] then rm -rf /Test/CYCLE_LOG/FLAG01 fi fi if [ ! -f "/Test/CYCLE_LOG/FLAG02" ] && [ ! -f "/Test/CYCLE_LOG/first.tmp" ] then if [ ! -z "`ls /Test/CYCLE_LOG/PCIE_SCAN/ | grep $count.log`" ] then count+=1 echo $count > /Test/CYCLE_LOG/count.log fi else if [ -f "/Test/CYCLE_LOG/FLAG02" ] then rm -rf /Test/CYCLE_LOG/FLAG02 fi fi sync if [ -f "/Test/CYCLE_LOG/first.tmp" ] then rm -rf /Test/CYCLE_LOG/first.tmp fi clear echo "******************************************************" echo "* *" echo "* System is starting the $count times cycle test ... " echo "* *" echo "******************************************************" read -p "Press [c] to stop testing! " -t 5 -n 1 stop if [ "$stop" = "c" ] then echo 0 > /sys/class/rtc/rtc0/wakealarm CLEAR_LOG exit 0 fi PCIE_SCAN DISK_SCAN #RW_TEST USB_SCAN MAC_SCAN SPECIAL_SCAN #PKTGEN_TEST #STRESS #PING_TEST DMESG TIME_STAMP if [ "$count" -ge "$goal" ] then CLEAR_LOG clear echo "******************************************************" echo "* *" echo "* The power cycle test has been finished! *" echo "* *" echo "******************************************************" read -p "Press any key to continue! " -n 1 continue else echo 1 > /Test/CYCLE_LOG/FLAG01 count+=1 echo $count > /Test/CYCLE_LOG/count.log echo 1 > /Test/CYCLE_LOG/FLAG02 sync clear echo "******************************************************" echo "* *" echo "* The `expr $count - 1` times cycle test is completed ... " echo "* *" echo "******************************************************" sleep 1 POWER_CYCLE fi fi else declare -i count=1 if [ -z "$2" ] then DEBUG $1 else DEBUG $1 $2 fi fi 帮忙将这个脚本优化一下,我只是用来计数开关机的次数,只要开机能显示执行了多少次的效果,其他多余的部分请帮忙删除
07-25
# -*- coding: utf-8 -*- """整合气象数据获取与处理系统 功能: 1. 在5分钟整点(0分、5分、10分等)获取实况气象数据 2. 将5分钟数据按月保存到Excel(存储在"5分钟级数据"文件夹) 3. 将5分钟数据插值为分钟级数据 4. 计算每分钟的太阳位置(高度角、方位角)和地外辐照度(保留两位小数) 5. 将分钟级数据按月保存到独立Excel(存储在"分钟级数据"文件夹) """ import urllib, urllib3, sys, uuid import ssl import json from openpyxl import Workbook, load_workbook from datetime import datetime, timedelta import warnings from urllib3.exceptions import InsecureRequestWarning import time import os import pandas as pd import numpy as np from scipy.interpolate import CubicSpline import math import openpyxl from openpyxl.styles import PatternFill, Font, Alignment import traceback # 强制刷新标准输出 - 确保实时输出 sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ if hasattr(sys.stdout, 'reconfigure'): sys.stdout.reconfigure(line_buffering=True) # 确保实时输出 else: # 对于不支持reconfigure的环境 sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1) # 禁用SSL警告 warnings.filterwarnings("ignore", category=InsecureRequestWarning) # 创建绕过SSL验证的连接池 http = urllib3.PoolManager(cert_reqs='CERT_NONE') # API配置 host = 'http://aliv18.data.moji.com' condition_path = '/whapi/json/alicityweather/condition' method = 'POST' appcode = '2c642e12da774c918fa78ac56b5b4c50' # 保定地理位置 LOCATION_NAME = "保定" LONGITUDE = 115.480 # 东经 LATITUDE = 38.855 # 北纬 # 定义API请求头 API_HEADERS = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Authorization': 'APPCODE ' + appcode } # 实况数据API参数 CONDITION_TOKEN = '50b53ff8dd7d9fa320d3d3ca32cf8ed1' CITY_ID = '1819' # 保定城市ID # 创建数据存储目录 FIVEMIN_DIR = "5分钟级数据" MINUTELY_DIR = "分钟级数据" os.makedirs(FIVEMIN_DIR, exist_ok=True) os.makedirs(MINUTELY_DIR, exist_ok=True) def log_message(message): """记录日志到屏幕 - 确保实时输出""" timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') log_line = f"[{timestamp}] {message}" # 直接输出控制台,强制刷新 print(log_line, flush=True) # 同时写入日志文件以便调试 with open("weather_system.log", "a", encoding="utf-8") as log_file: log_file.write(log_line + "\n") log_file.flush() # 立即刷新文件写入 def safe_save(wb, filename): """安全保存Excel文件,避免占用问题""" log_message(f"正在保存文件: {filename}") # 确保目标目录存在 os.makedirs(os.path.dirname(filename), exist_ok=True) for attempt in range(5): # 增加尝试次数 try: # 使用绝对路径避免相对路径问题 abs_filename = os.path.abspath(filename) temp_file = abs_filename.replace(".xlsx", f"_temp_{attempt}.xlsx") log_message(f"尝试保存临时文件: {temp_file}") wb.save(temp_file) # 替换原文件 if os.path.exists(abs_filename): os.remove(abs_filename) os.rename(temp_file, abs_filename) log_message(f"文件保存成功: {abs_filename}") return True except (PermissionError, OSError) as e: log_message(f"文件保存失败 ({attempt+1}/5): {str(e)}") time.sleep(3) except Exception as e: log_message(f"文件保存时发生意外错误: {str(e)}") traceback.print_exc() time.sleep(3) return False def get_condition_data(): """获取实况天气数据""" try: log_message(f"正在获取{LOCATION_NAME}实况天气数据...") condition_bodys = {'token': CONDITION_TOKEN, 'cityId': CITY_ID} post_data_condition = urllib.parse.urlencode(condition_bodys).encode('utf-8') condition_url = host + condition_path response_condition = http.request('POST', condition_url, body=post_data_condition, headers=API_HEADERS) content_condition = response_condition.data.decode('utf-8') condition_data = json.loads(content_condition) log_message(f"API响应内容: {json.dumps(condition_data, ensure_ascii=False)[:200]}...") if condition_data.get('code') != 0: log_message(f"实况API请求失败: 代码 {condition_data.get('code')}, 消息: {condition_data.get('msg')}") return None condition_info = condition_data['data']['condition'] current_time = datetime.now() # 对齐到最近的5分钟 aligned_minute = (current_time.minute // 5) * 5 aligned_time = current_time.replace(minute=aligned_minute, second=0, microsecond=0) time_str = aligned_time.strftime("%Y-%m-%d %H:%M") # 计算风速(m/s)并保留一位小数 raw_wind_speed = condition_info.get('windSpeed', '') wind_speed_mps = '' if raw_wind_speed and raw_wind_speed.replace('.', '', 1).isdigit(): try: wind_speed_mps = round(float(raw_wind_speed) / 3.6, 1) # 保留一位小数 except: wind_speed_mps = '' # 处理温度值,确保保留一位小数 temp_value = condition_info.get('temp', '') if temp_value and temp_value.replace('.', '', 1).isdigit(): try: temp_value = round(float(temp_value), 1) # 温度保留一位小数 except: pass # 构建实况数据行 condition_row = [ time_str, temp_value, # 温度保留一位小数 condition_info.get('condition', ''), condition_info.get('humidity', ''), condition_info.get('windDir', ''), condition_info.get('windLevel', ''), raw_wind_speed, wind_speed_mps, # 风速保留一位小数 condition_info.get('precip', '0.0'), condition_info.get('pressure', '') ] log_message(f"成功获取实况数据: {time_str}") log_message(f" 温度: {temp_value}℃, 天气状况: {condition_info.get('condition', '')}, 湿度: {condition_info.get('humidity', '')}%") return condition_row except Exception as e: log_message(f"获取实况数据时出错: {str(e)}") traceback.print_exc() return None def normalize_time(time_str): """统一时间格式为 YYYY-MM-DD HH:MM""" try: # 如果已经是字符串,尝试解析 if isinstance(time_str, str): # 尝试解析为日期时间 if len(time_str) == 16: # 格式为 "YYYY-MM-DD HH:MM" return time_str elif len(time_str) == 19: # 包含秒数 "YYYY-MM-DD HH:MM:00" return time_str[:16] elif ' ' not in time_str: # 只有日期部分 return time_str + " 00:00" else: # 其他格式,尝试转换 dt = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S") return dt.strftime("%Y-%m-%d %H:%M") # 如果是datetime对象 elif isinstance(time_str, datetime): return time_str.strftime("%Y-%m-%d %H:%M") except Exception: pass # 无法识别的格式,原样返回 return str(time_str) def update_fivemin_excel(condition_row): """更新5分钟级Excel文件""" try: current_month = datetime.now().strftime("%Y%m") # 确保目录存在 os.makedirs(FIVEMIN_DIR, exist_ok=True) filename = os.path.join(os.path.abspath(FIVEMIN_DIR), f"{LOCATION_NAME}_5分钟级数据_{current_month}.xlsx") wb = None ws = None existing_data = {} # 存储时间点 -> 行号的映射 headers = [] log_message(f"正在更新5分钟数据文件: {filename}") if os.path.exists(filename): for attempt in range(3): try: log_message(f"尝试加载现有5分钟数据文件... (尝试 {attempt+1}/3)") wb = load_workbook(filename) ws = wb.active if ws.max_row > 0: headers = [cell.value for cell in ws[1]] # 读取现有数据到字典 (时间 -> 行号) for row_idx, row in enumerate(ws.iter_rows(min_row=2, values_only=True), start=2): if not row or not row[0]: continue time_key = normalize_time(row[0]) if time_key in existing_data: log_message(f"警告: 发现重复时间点: {time_key} (行 {row_idx})") existing_data[time_key] = row_idx log_message(f"成功加载现有5分钟数据文件: {filename} (共 {len(existing_data)} 条记录)") break except PermissionError: if attempt < 2: log_message(f"文件被占用,等待5秒后重试 ({attempt+1}/3)") time.sleep(5) else: log_message("无法打开文件,创建新工作簿") wb = Workbook() ws = wb.active ws.title = f"{LOCATION_NAME}5分钟级数据" headers = ["时间", "温度(℃)", "天气状况", "湿度(%)", "风向", "风力等级", "原始风速(km/h)", "风速(m/s)", "降水量(mm)", "气压(hPa)"] ws.append(headers) else: wb = Workbook() ws = wb.active ws.title = f"{LOCATION_NAME}5分钟极数据" headers = ["时间", "温度(℃)", "天气状况", "湿度(%)", "风向", "风力等级", "原始风速(km/h)", "风速(m/s)", "降水量(mm)", "气压(hPa)"] ws.append(headers) log_message(f"创建新的5分钟数据文件: {filename}") if not headers: headers = ["时间", "温度(℃)", "天气状况", "湿度(%)", "风向", "风力等级", "原始风速(km/h)", "风速(m/s)", "降水量(mm)", "气压(hPa)"] # 处理实况数据 if condition_row: current_time = condition_row[0] normalized_current = normalize_time(current_time) if normalized_current in existing_data: row_idx = existing_data[normalized_current] # 更新所有字段(覆盖旧数据) for col_idx in range(1, len(condition_row) + 1): new_value = condition_row[col_idx - 1] ws.cell(row=row_idx, column=col_idx, value=new_value) log_message(f"更新5分钟时间点: {normalized_current} (行 {row_idx})") else: ws.append(condition_row) # 更新字典,记录新行号 existing_data[normalized_current] = ws.max_row log_message(f"新增5分钟时间点: {normalized_current} (行 {ws.max_row})") # 保存文件 if safe_save(wb, filename): log_message(f"5分钟数据保存成功: {filename}") return filename else: log_message(f"5分钟数据保存失败") return None except Exception as e: log_message(f"更新5分钟数据文件时出错: {str(e)}") traceback.print_exc() return None def calculate_solar_parameters(dt, longitude, latitude): """计算太阳高度角、方位角和地外辐照度(高度角和方位角保留两位小数)""" try: # 将时间转换为UTC+0 utc_time = dt - timedelta(hours=8) n = utc_time.timetuple().tm_yday # 年中的第几天 # 计算太阳赤纬 (δ) delta = 23.45 * math.sin(math.radians(360 * (284 + n) / 365)) delta_rad = math.radians(delta) # 计算时角 (ω) utc_hour = utc_time.hour + utc_time.minute/60.0 omega = (utc_hour - 12) * 15 + longitude omega_rad = math.radians(omega) # 纬度转弧度 phi_rad = math.radians(latitude) # 计算太阳高度角 (α) sin_alpha = math.sin(phi_rad) * math.sin(delta_rad) + math.cos(phi_rad) * math.cos(delta_rad) * math.cos(omega_rad) alpha = math.degrees(math.asin(sin_alpha)) # 计算太阳方位角 (γ) sin_gamma = -math.cos(delta_rad) * math.sin(omega_rad) / math.cos(math.radians(alpha)) cos_gamma = (math.sin(delta_rad) * math.cos(phi_rad) - math.cos(delta_rad) * math.sin(phi_rad) * math.cos(omega_rad)) / math.cos(math.radians(alpha)) gamma = math.degrees(math.atan2(sin_gamma, cos_gamma)) gamma = (gamma + 360) % 360 # 转换为0-360度范围 # 计算地外辐照度 (W/m²) g0 = 1367 * (1 + 0.033 * math.cos(math.radians(360 * n / 365))) * sin_alpha g0 = max(0, g0) # 确保非负 # 保留两位小数 return round(alpha, 2), round(gamma, 2), round(g0, 1) except Exception as e: log_message(f"计算太阳参数错误: {str(e)}") return None, None, None def process_minutely_data(fivemin_file): """处理分钟级数据并添加太阳参数""" try: log_message("="*50) log_message(f"开始生成分钟级数据...") # 检查文件是否存在 if not os.path.exists(fivemin_file): log_message(f"错误: 5分钟数据文件不存在: {fivemin_file}") return None # 读取5分钟数据 log_message(f"读取5分钟数据文件: {fivemin_file}") try: fivemin_df = pd.read_excel(fivemin_file) log_message(f"读取5分钟数据成功,共 {len(fivemin_df)} 行") except Exception as e: log_message(f"读取5分钟数据文件失败: {str(e)}") return None # 查找时间列 time_col = next((col for col in fivemin_df.columns if '时间' in col), None) if not time_col: log_message("未找到时间列") return None # 转换时间格式并处理重复值 fivemin_df[time_col] = pd.to_datetime(fivemin_df[time_col], errors='coerce') # 删除无效行 original_count = len(fivemin_df) fivemin_df = fivemin_df.dropna(subset=[time_col]) if original_count > len(fivemin_df): log_message(f"删除了 {original_count - len(fivemin_df)} 行无效时间数据") # 处理重复时间点 - 保留最后一个 duplicate_mask = fivemin_df.duplicated(subset=[time_col], keep='last') if duplicate_mask.any(): log_message(f"发现 {duplicate_mask.sum()} 个重复时间点,保留最后一个") fivemin_df = fivemin_df[~duplicate_mask] # 按时间排序 fivemin_df = fivemin_df.sort_values(by=time_col) fivemin_df.set_index(time_col, inplace=True) # 创建分钟级时间索引 start_time = fivemin_df.index.min() end_time = fivemin_df.index.max() log_message(f"时间范围: {start_time} 至 {end_time}") minutely_index = pd.date_range(start=start_time, end=end_time, freq='1min') minutely_df = pd.DataFrame(index=minutely_index) log_message(f"将生成 {len(minutely_index)} 条分钟级数据") # 插值处理 - 确保时间戳严格递增 base_time = start_time fivemin_timestamps = (fivemin_df.index - base_time).total_seconds() # 检查时间戳是否严格递增 if not (np.diff(fivemin_timestamps) > 0).all(): log_message("时间戳不是严格递增,尝试修复...") # 重新排序 fivemin_df = fivemin_df.sort_index() fivemin_timestamps = (fivemin_df.index - base_time).total_seconds() minutely_timestamps = (minutely_df.index - base_time).total_seconds() # 对连续参数进行插值 log_message("\n开始数据插值处理...") for param in ['风速(m/s)', '温度(℃)', '湿度(%)', '气压(hPa)']: if param in fivemin_df.columns: param_data = fivemin_df[param].dropna() if len(param_data) >= 3: log_message(f"对 {param} 使用三次样条插值 (数据点: {len(param_data)})") cs = CubicSpline(fivemin_timestamps, param_data.values) interpolated_values = cs(minutely_timestamps) # 对温度和风速保留一位小数 if param in ['温度(℃)', '风速(m/s)']: interpolated_values = np.round(interpolated_values, 1) minutely_df[param] = interpolated_values else: log_message(f"对 {param} 使用前向填充 (有效点不足: {len(param_data)})") minutely_df[param] = fivemin_df[param].resample('1min').ffill() # 处理降水量 if '降水量(mm)' in fivemin_df.columns: log_message("处理降水量数据") # 将5分钟降水量转换为每分钟降水量 precip_min = fivemin_df['降水量(mm)'].resample('1min').asfreq().ffill() minutely_df['降水量(mm)'] = precip_min / 5.0 # 平均分配到每分钟 # 处理文本数据 for param in ['天气状况', '风向']: if param in fivemin_df.columns: log_message(f"处理 {param} 数据") minutely_df[param] = fivemin_df[param].resample('1min').ffill() # 数值列保留适当的小数位数 # 温度和风速保留一位小数 if '温度(℃)' in minutely_df.columns: minutely_df['温度(℃)'] = minutely_df['温度(℃)'].round(1) if '风速(m/s)' in minutely_df.columns: minutely_df['风速(m/s)'] = minutely_df['风速(m/s)'].round(1) # 其他数值列保留一位小数 other_numeric_cols = ['湿度(%)', '气压(hPa)', '降水量(mm)'] for col in other_numeric_cols: if col in minutely_df.columns: minutely_df[col] = minutely_df[col].round(1) # 计算太阳参数 log_message(f"\n开始计算太阳位置和辐照度...") solar_data = [] total_points = len(minutely_df) last_progress = -1 start_time = time.time() for i, dt in enumerate(minutely_df.index): alpha, gamma, g0 = calculate_solar_parameters(dt, LONGITUDE, LATITUDE) solar_data.append({ '太阳高度角(度)': alpha, '太阳方位角(度)': gamma, '地外辐照度(W/m2)': g0 }) # 显示进度 progress = int((i + 1) / total_points * 100) if progress != last_progress and progress % 10 == 0: elapsed = time.time() - start_time remaining = (total_points - i) * (elapsed / (i+1)) log_message(f"计算进度: {progress}% | 预计剩余时间: {remaining:.1f}秒") last_progress = progress solar_df = pd.DataFrame(solar_data, index=minutely_df.index) minutely_df = pd.concat([minutely_df, solar_df], axis=1) # 生成输出文件名 current_month = datetime.now().strftime("%Y%m") filename = f"{LOCATION_NAME}_分钟级数据_{current_month}.xlsx" filepath = os.path.join(os.path.abspath(MINUTELY_DIR), filename) # 保存分钟级数据 minutely_df.reset_index(inplace=True) minutely_df.rename(columns={'index': '时间'}, inplace=True) # 创建Excel工作簿 wb = openpyxl.Workbook() ws = wb.active ws.title = "分钟级数据" # 写入数据 log_message(f"\n正在写入分钟级数据到Excel...") for col_idx, col_name in enumerate(minutely_df.columns, 1): ws.cell(row=1, column=col_idx, value=col_name) for r_idx, row in enumerate(minutely_df.values, 2): for c_idx, value in enumerate(row, 1): ws.cell(row=r_idx, column=c_idx, value=value) # 应用样式 header_fill = PatternFill(start_color="1F4E78", end_color="1F4E78", fill_type="solid") header_font = Font(color="FFFFFF", bold=True) header_alignment = Alignment(horizontal="center", vertical="center") for cell in ws[1]: cell.fill = header_fill cell.font = header_font cell.alignment = header_alignment # 设置列宽 log_message("设置列宽...") for col in ws.columns: max_length = 0 for cell in col: try: if cell.value and len(str(cell.value)) > max_length: max_length = len(str(cell.value)) except: pass adjusted_width = (max_length + 2) * 1.2 ws.column_dimensions[col[0].column_letter].width = min(adjusted_width, 50) # 保存文件 if safe_save(wb, filepath): log_message(f"分钟级数据保存成功: {filepath}") return filepath else: log_message(f"分钟级数据保存失败") return None except Exception as e: log_message(f"处理分钟级数据时出错: {str(e)}") traceback.print_exc() return None def get_weather_data(): """获取天气数据并处理""" log_message(f"\n获取{LOCATION_NAME}实况天气数据...") try: # 获取实况数据 condition_row = get_condition_data() if not condition_row: log_message("获取实况数据失败") return False # 更新5分钟数据文件 fivemin_file = update_fivemin_excel(condition_row) if not fivemin_file: log_message("5分钟数据更新失败") return False # 处理分钟级数据(只在5分钟整点处理) current_minute = datetime.now().minute if current_minute % 5 == 0: # 0分、5分、10分等 log_message(f"当前时间 {datetime.now().strftime('%H:%M')} 是5分钟整点,开始生成分钟级数据") minutely_file = process_minutely_data(fivemin_file) if minutely_file: log_message(f"\n数据处理完成!") log_message(f" 5分钟数据 -> {fivemin_file}") log_message(f" 分钟数据 -> {minutely_file}") else: log_message(f"分钟数据处理失败") else: log_message(f"跳过分钟级数据处理(非5分钟整点)") return True except Exception as e: log_message(f"获取天气数据时出错: {str(e)}") traceback.print_exc() return False # 主程序循环 - 确保实时输出日志 if __name__ == '__main__': try: # 程序启动横幅 - 使用print确保直接输出 print("=" * 70, flush=True) print(f"{LOCATION_NAME}气象数据自动获取与处理系统", flush=True) print(f"系统启动时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", flush=True) print(f"Python版本: {sys.version}", flush=True) print(f"工作目录: {os.getcwd()}", flush=True) print(f"5分钟数据存储目录: {os.path.abspath(FIVEMIN_DIR)}", flush=True) print(f"分钟数据存储目录: {os.path.abspath(MINUTELY_DIR)}", flush=True) print("=" * 70, flush=True) print("按 Ctrl+C 停止程序", flush=True) print("=" * 70, flush=True) # 初始执行一次 log_message("\n执行初始数据获取...") success = get_weather_data() # 主循环 current_month = datetime.now().month while True: try: # 计算到下一个整分钟的时间(确保在0秒执行) now = datetime.now() next_minute = now.replace(second=0, microsecond=0) + timedelta(minutes=1) wait_seconds = (next_minute - now).total_seconds() if wait_seconds > 0: wait_minutes = wait_seconds / 60 log_message(f"\n等待 {wait_seconds:.1f} 秒 ({wait_minutes:.2f} 分钟) 到下一个整分钟") time.sleep(wait_seconds) # 检查月份变化 new_month = datetime.now().month if new_month != current_month: log_message(f"\n月份变更: {current_month} -> {new_month}") current_month = new_month # 获取并处理数据 log_message("\n" + "="*70) log_message(f"开始新一轮数据采集 ({datetime.now().strftime('%Y-%m-%d %H:%M:%S')})") success = get_weather_data() except KeyboardInterrupt: log_message("\n程序已停止") break except Exception as e: # 获取详细错误信息 exc_type, exc_value, exc_traceback = sys.exc_info() error_details = traceback.format_exception(exc_type, exc_value, exc_traceback) error_msg = ''.join(error_details) log_message(f"\n主循环错误: {str(e)}") log_message(f"详细错误信息:\n{error_msg}") log_message("5分钟后重试...") time.sleep(300) # 5分钟后重试 # 重新计算下一个整分钟时间 now = datetime.now() next_minute = now.replace(second=0, microsecond=0) + timedelta(minutes=1) current_month = datetime.now().month log_message(f"新的重试时间: {next_minute.strftime('%Y-%m-%d %H:%M:%S')}") except Exception as e: # 启动错误处理 print(f"程序启动失败: {str(e)}", flush=True) traceback.print_exc(file=sys.stdout)把这段程序也用上面那个方法实现在Python程序在运行时在页面显示结果
07-16
Microsoft Windows [版本 10.0.22631.2861] (c) Microsoft Corporation。保留所有权利。 C:\Users\Administrator>cd /d E:\AI_System\web_ui E:\AI_System\web_ui>python server.py 2025-08-12 03:55:11,438 - CoreInit - INFO - Core module initialization started 2025-08-12 03:55:11,438 - EnvironmentManager - INFO - 环境管理器初始化完成 (基础目录: E:\AI_System\data\environment) 2025-08-12 03:55:11,438 - CoreInit - INFO - Environment manager created: DefaultEnvironment 2025-08-12 03:55:11,438 - CoreInit - INFO - Core module initialized successfully 2025-08-12 03:55:11,447 - CoreConfig - INFO - 📋 初始化配置管理器 | 环境前缀: | 基础目录: E:\AI_System\web_ui --- Logging error --- Traceback (most recent call last): File "E:\Python310\lib\logging\__init__.py", line 1103, in emit stream.write(msg + self.terminator) UnicodeEncodeError: 'gbk' codec can't encode character '\U0001f4cb' in position 46: illegal multibyte sequence Call stack: File "E:\AI_System\web_ui\server.py", line 23, in <module> system_config = SystemConfig() File "E:\AI_System\core\config.py", line 40, in __init__ self._initialize() File "E:\AI_System\core\config.py", line 44, in _initialize self.logger.info(f"📋 初始化配置管理器 | 环境前缀: {self.env_prefix} | 基础目录: {Path.cwd()}") Message: '📋 初始化配置管理器 | 环境前缀: | 基础目录: E:\\AI_System\\web_ui' Arguments: () 2025-08-12 03:55:11,448 - CoreConfig - INFO - 🔍 加载环境变量... --- Logging error --- Traceback (most recent call last): File "E:\Python310\lib\logging\__init__.py", line 1103, in emit stream.write(msg + self.terminator) UnicodeEncodeError: 'gbk' codec can't encode character '\U0001f50d' in position 46: illegal multibyte sequence Call stack: File "E:\AI_System\web_ui\server.py", line 23, in <module> system_config = SystemConfig() File "E:\AI_System\core\config.py", line 40, in __init__ self._initialize() File "E:\AI_System\core\config.py", line 47, in _initialize self._load_environment() File "E:\AI_System\core\config.py", line 63, in _load_environment self.logger.info("🔍 加载环境变量...") Message: '🔍 加载环境变量...' Arguments: () 2025-08-12 03:55:11,449 - CoreConfig - WARNING - ⚠️ 配置文件不存在: None --- Logging error --- Traceback (most recent call last): File "E:\Python310\lib\logging\__init__.py", line 1103, in emit stream.write(msg + self.terminator) UnicodeEncodeError: 'gbk' codec can't encode character '\u26a0' in position 49: illegal multibyte sequence Call stack: File "E:\AI_System\web_ui\server.py", line 23, in <module> system_config = SystemConfig() File "E:\AI_System\core\config.py", line 40, in __init__ self._initialize() File "E:\AI_System\core\config.py", line 53, in _initialize self.logger.warning(f"⚠️ 配置文件不存在: {self.config_path}") Message: '⚠️ 配置文件不存在: None' Arguments: () 2025-08-12 03:55:11,452 - CoreConfig - INFO - 🔄 合并默认配置... --- Logging error --- Traceback (most recent call last): File "E:\Python310\lib\logging\__init__.py", line 1103, in emit stream.write(msg + self.terminator) UnicodeEncodeError: 'gbk' codec can't encode character '\U0001f504' in position 46: illegal multibyte sequence Call stack: File "E:\AI_System\web_ui\server.py", line 23, in <module> system_config = SystemConfig() File "E:\AI_System\core\config.py", line 40, in __init__ self._initialize() File "E:\AI_System\core\config.py", line 56, in _initialize self._merge_defaults() File "E:\AI_System\core\config.py", line 126, in _merge_defaults self.logger.info("🔄 合并默认配置...") Message: '🔄 合并默认配置...' Arguments: () 2025-08-12 03:55:11,454 - CoreConfig - INFO - ✅ 配置加载完成 | 条目数: 52 --- Logging error --- Traceback (most recent call last): File "E:\Python310\lib\logging\__init__.py", line 1103, in emit stream.write(msg + self.terminator) UnicodeEncodeError: 'gbk' codec can't encode character '\u2705' in position 46: illegal multibyte sequence Call stack: File "E:\AI_System\web_ui\server.py", line 23, in <module> system_config = SystemConfig() File "E:\AI_System\core\config.py", line 40, in __init__ self._initialize() File "E:\AI_System\core\config.py", line 56, in _initialize self._merge_defaults() File "E:\AI_System\core\config.py", line 128, in _merge_defaults self.logger.info(f"✅ 配置加载完成 | 条目数: {len(self._config)}") Message: '✅ 配置加载完成 | 条目数: 52' Arguments: () 2025-08-12 03:55:11 - WebServer - INFO - 14196 - 5264 - ✅ 日志系统初始化完成 2025-08-12 03:55:11,455 - WebServer - INFO - ✅ 日志系统初始化完成 --- Logging error --- Traceback (most recent call last): File "E:\Python310\lib\logging\__init__.py", line 1103, in emit stream.write(msg + self.terminator) UnicodeEncodeError: 'gbk' codec can't encode character '\u2705' in position 45: illegal multibyte sequence Call stack: File "E:\AI_System\web_ui\server.py", line 95, in <module> logger = setup_logger() File "E:\AI_System\web_ui\server.py", line 87, in setup_logger logger.info("✅ 日志系统初始化完成") Message: '✅ 日志系统初始化完成' Arguments: () 2025-08-12 03:55:11 - WebServer - INFO - 14196 - 5264 - ✅ 日志系统初始化完成 2025-08-12 03:55:11 - WebServer - INFO - 14196 - 5264 - 📝 日志级别: INFO 2025-08-12 03:55:11,456 - WebServer - INFO - 📝 日志级别: INFO --- Logging error --- Traceback (most recent call last): File "E:\Python310\lib\logging\__init__.py", line 1103, in emit stream.write(msg + self.terminator) UnicodeEncodeError: 'gbk' codec can't encode character '\U0001f4dd' in position 45: illegal multibyte sequence Call stack: File "E:\AI_System\web_ui\server.py", line 95, in <module> logger = setup_logger() File "E:\AI_System\web_ui\server.py", line 88, in setup_logger logger.info(f"📝 日志级别: {'DEBUG' if debug_mode else 'INFO'}") Message: '📝 日志级别: INFO' Arguments: () 2025-08-12 03:55:11 - WebServer - INFO - 14196 - 5264 - 📝 日志级别: INFO 2025-08-12 03:55:11 - WebServer - INFO - 14196 - 5264 - 📁 日志文件: web_server.log 2025-08-12 03:55:11,457 - WebServer - INFO - 📁 日志文件: web_server.log --- Logging error --- Traceback (most recent call last): File "E:\Python310\lib\logging\__init__.py", line 1103, in emit stream.write(msg + self.terminator) UnicodeEncodeError: 'gbk' codec can't encode character '\U0001f4c1' in position 45: illegal multibyte sequence Call stack: File "E:\AI_System\web_ui\server.py", line 95, in <module> logger = setup_logger() File "E:\AI_System\web_ui\server.py", line 89, in setup_logger logger.info(f"📁 日志文件: {log_file}") Message: '📁 日志文件: web_server.log' Arguments: () 2025-08-12 03:55:11 - WebServer - INFO - 14196 - 5264 - 📁 日志文件: web_server.log Traceback (most recent call last): File "E:\AI_System\web_ui\server.py", line 669, in <module> app, socketio = create_app() File "E:\AI_System\web_ui\server.py", line 643, in create_app system_initializer = SystemInitializer() File "E:\AI_System\web_ui\server.py", line 321, in __init__ logger.info(f"系统初始化器创建, 基础目录: {system_config.BASE_DIR}") File "E:\AI_System\core\config.py", line 188, in __getattr__ raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") AttributeError: 'CoreConfig' object has no attribute 'BASE_DIR' E:\AI_System\web_ui>
最新发布
08-13
下次请把要修改的文件的位置,名称告诉我 然后我把文件发给你,你改好了(要完整的),再还给我,这是E:\AI_System\agent里的environment_interface.py:“import os import psutil import platform import json import sqlite3 import sys import subprocess import requests import logging from datetime import datetime from pathlib import Path logger = logging.getLogger('EnvironmentInterface') class EnvironmentInterface: def __init__(self, base_dir: str): # 配置日志 self.logger = logging.getLogger('EnvironmentInterface') self.logger.setLevel(logging.INFO) console_handler = logging.StreamHandler() console_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) self.logger.addHandler(console_handler) self.logger.propagate = False # 工作区路径设置(使用绝对路径) self.workspace_root = self._resolve_workspace_path(base_dir) # 解析路径并确保目录存在 self.models_dir = self._resolve_and_create_dir(os.path.join(self.workspace_root, "01_模型存储")) self.cache_dir = self._resolve_and_create_dir(os.path.join(self.workspace_root, "01_模型存储", "下载缓存")) self.system_dir = self._resolve_and_create_dir(os.path.join(self.workspace_root, "02_核心代码")) self.temp_dir = self._resolve_and_create_dir(os.path.join(self.workspace_root, "04_环境工具", "临时补丁")) self.python_dir = self._resolve_and_create_dir(os.path.join(self.workspace_root, "04_环境工具", "Python环境")) # 环境配置 os.environ['PATH'] = f"{self.python_dir};{self.python_dir}\\Scripts;{os.environ['PATH']}" os.environ['HF_HOME'] = self.cache_dir # 安全策略 self.authorized_actions = { "file_access": True, "web_search": True, "command_exec": True, "software_install": False, "hardware_control": False } self.action_log = [] # 初始化数据库(使用绝对路径) self.environment_db = os.path.join(self.system_dir, 'environment.db') self._init_db() self.logger.info("✅ 环境接口初始化完成") def _resolve_workspace_path(self, base_dir: str) -> str: """解析工作区路径为绝对路径""" try: # 使用Path对象确保跨平台兼容性 base_path = Path(base_dir).resolve() workspace_path = base_path / "AI_Workspace" if not workspace_path.exists(): workspace_path.mkdir(parents=True, exist_ok=True) self.logger.info(f"创建工作区目录: {workspace_path}") return str(workspace_path) except Exception as e: self.logger.error(f"工作区路径解析失败: {str(e)}") # 回退到默认路径 fallback_path = os.path.join(os.path.expanduser("~"), "AI_Workspace") os.makedirs(fallback_path, exist_ok=True) return fallback_path def _resolve_and_create_dir(self, path): """解析路径并确保目录存在""" try: # 转换为绝对路径 abs_path = os.path.abspath(path) # 创建目录(如果不存在) if not os.path.exists(abs_path): os.makedirs(abs_path, exist_ok=True) self.logger.info(f"创建目录: {abs_path}") return abs_path except Exception as e: self.logger.error(f"目录解析失败: {path} - {str(e)}") # 创建临时目录作为回退 temp_path = os.path.join(self.workspace_root, "temp") os.makedirs(temp_path, exist_ok=True) return temp_path def _init_db(self): """初始化环境数据库""" try: conn = sqlite3.connect(self.environment_db) c = conn.cursor() # 系统信息表 c.execute('''CREATE TABLE IF NOT EXISTS system_info ( id INTEGER PRIMARY KEY, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, os TEXT, cpu TEXT, memory REAL, disk_usage REAL )''') # 文件探索历史表 c.execute('''CREATE TABLE IF NOT EXISTS file_exploration ( id INTEGER PRIMARY KEY, path TEXT UNIQUE, last_visited DATETIME, visit_count INTEGER DEFAULT 0 )''') # 资源管理表 c.execute('''CREATE TABLE IF NOT EXISTS resources ( id INTEGER PRIMARY KEY, name TEXT, type TEXT CHECK(type IN ('skin', 'furniture', 'tool')), path TEXT, is_active BOOLEAN DEFAULT 0 )''') conn.commit() conn.close() self.logger.info(f"✅ 数据库初始化完成: {self.environment_db}") except Exception as e: self.logger.error(f"❌ 数据库初始化失败: {str(e)}") # 系统监控功能 def get_system_info(self): """获取并记录系统信息""" try: # 获取内存使用情况 mem = psutil.virtual_memory() mem_used = round(mem.used / (1024 ** 3), 1) mem_total = round(mem.total / (1024 ** 3), 1) # 获取磁盘使用情况 disk_usage = psutil.disk_usage('/').percent info = { "os": f"{platform.system()} {platform.release()}", "cpu": f"{platform.processor()} ({psutil.cpu_count(logical=False)} cores)", "memory": f"{mem_used}GB/{mem_total}GB", "disk_usage": f"{disk_usage}%" } # 保存到数据库 conn = sqlite3.connect(self.environment_db) c = conn.cursor() c.execute('''INSERT INTO system_info (os, cpu, memory, disk_usage) VALUES (?, ?, ?, ?)''', (info['os'], info['cpu'], mem_used, disk_usage)) conn.commit() conn.close() self.log_action("system_monitor", "采集系统信息") return info except Exception as e: self.logger.error(f"❌ 获取系统信息失败: {str(e)}") return { "os": f"Error: {str(e)}", "cpu": "0%", "memory": "0GB/0GB", "disk_usage": "0%" } # 文件探索功能 def explore_directory(self, path=None): """探索目录内容""" try: target_path = path or self.workspace_root target_path = os.path.abspath(target_path) # 安全路径检查 if not target_path.startswith(os.path.abspath(self.workspace_root)): return {"error": "访问路径超出工作区范围"} if not os.path.exists(target_path): return {"error": "路径不存在"} # 记录探索历史 self._record_exploration(target_path) contents = [] for item in os.listdir(target_path): full_path = os.path.join(target_path, item) try: is_dir = os.path.isdir(full_path) size = os.path.getsize(full_path) if not is_dir else 0 modified_time = os.path.getmtime(full_path) contents.append({ "name": item, "type": "directory" if is_dir else "file", "path": full_path, "size": f"{size / 1024:.1f}KB" if size < 1024 ** 2 else f"{size / (1024 ** 2):.1f}MB", "modified": datetime.fromtimestamp(modified_time).strftime("%Y-%m-%d %H:%M") }) except PermissionError: contents.append({ "name": item, "type": "unknown", "error": "权限不足" }) except Exception as e: contents.append({ "name": item, "type": "unknown", "error": str(e) }) self.log_action("file_explore", f"探索路径: {target_path}") return { "current_path": target_path, "contents": sorted(contents, key=lambda x: (x['type'] == 'directory', x['name']), reverse=True) } except Exception as e: self.logger.error(f"❌ 探索目录失败: {str(e)}") return {"error": str(e)} def _record_exploration(self, path): """记录探索历史到数据库""" try: conn = sqlite3.connect(self.environment_db) c = conn.cursor() c.execute("SELECT id FROM file_exploration WHERE path = ?", (path,)) if c.fetchone(): c.execute('''UPDATE file_exploration SET last_visited = CURRENT_TIMESTAMP, visit_count = visit_count + 1 WHERE path = ?''', (path,)) else: c.execute('''INSERT INTO file_exploration (path, last_visited, visit_count) VALUES (?, CURRENT_TIMESTAMP, 1)''', (path,)) conn.commit() except Exception as e: self.logger.error(f"❌ 记录探索历史失败: {str(e)}") finally: conn.close() # 资源管理功能 def get_resource(self, resource_type): """获取特定类型资源""" try: conn = sqlite3.connect(self.environment_db) c = conn.cursor() c.execute('''SELECT name, path, is_active FROM resources WHERE type = ?''', (resource_type,)) resources = [ {"name": item[0], "path": item[1], "is_active": bool(item[2])} for item in c.fetchall() ] return resources except Exception as e: self.logger.error(f"❌ 获取资源失败: {str(e)}") return [] finally: conn.close() def activate_resource(self, resource_name): """激活特定资源""" try: conn = sqlite3.connect(self.environment_db) c = conn.cursor() c.execute('''UPDATE resources SET is_active = 0 WHERE type = (SELECT type FROM resources WHERE name = ?)''', (resource_name,)) c.execute('''UPDATE resources SET is_active = 1 WHERE name = ?''', (resource_name,)) conn.commit() self.log_action("resource_activate", f"激活资源: {resource_name}") return True except Exception as e: self.logger.error(f"❌ 激活资源失败: {str(e)}") return False finally: conn.close() # 工作区管理功能 def get_workspace_info(self): """获取工作区信息""" return { "workspace": self.workspace_root, "models": self.models_dir, "system": self.system_dir, "cache": self.cache_dir, "temp": self.temp_dir, "python": self.python_dir } # 辅助功能 def _is_authorized(self, action): """检查操作授权状态""" return self.authorized_actions.get(action, False) def log_action(self, action, details): """记录环境操作日志""" log_entry = { "timestamp": datetime.now().isoformat(), "action": action, "details": details } self.action_log.append(log_entry) # 保存到文件 log_file = os.path.join(self.workspace_root, "environment_actions.log") try: with open(log_file, 'a', encoding='utf-8') as f: f.write(json.dumps(log_entry, ensure_ascii=False) + "\n") except Exception as e: self.logger.error(f"❌ 记录日志失败: {str(e)}") # 同时记录到logger self.logger.info(f"{action}: {details}") return True # 使用示例 if __name__ == "__main__": # 配置日志 logging.basicConfig(level=logging.INFO) # 创建环境接口实例 env = EnvironmentInterface(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # 获取工作区信息 print("工作区信息:", json.dumps(env.get_workspace_info(), indent=2, ensure_ascii=False)) # 获取系统信息 print("系统信息:", json.dumps(env.get_system_info(), indent=2, ensure_ascii=False)) # 探索目录 print("工作区内容:", json.dumps(env.explore_directory(), indent=2, ensure_ascii=False)) ”E:\AI_System\agent里的autonomous_agent.py:“import os import time import logging from dotenv import load_dotenv # 使用绝对导入 from core.config import system_config from core.environment import DefaultEnvironment, AIHome, ActionExecutor from .environment_interface import EnvironmentInterface # 导入修复后的环境接口 class AutonomousAgent: def __init__(self): self.logger = self._setup_logger() self.logger.info("🔁 初始化自主智能体核心模块...") try: # 加载环境变量 load_dotenv() # 初始化环境感知系统 self._initialize_environment_systems() # 初始化各子系统 self._initialize_subsystems() self.logger.info("✅ 自主智能体初始化完成") except Exception as e: self.logger.error(f"❌ 智能体初始化失败: {str(e)}") raise def _setup_logger(self): """配置日志记录器""" logger = logging.getLogger('AutonomousAgent') logger.setLevel(system_config.LOG_LEVEL) # 创建控制台处理器 console_handler = logging.StreamHandler() console_handler.setLevel(system_config.LOG_LEVEL) # 创建格式化器 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') console_handler.setFormatter(formatter) # 添加处理器 logger.addHandler(console_handler) logger.propagate = False return logger def _initialize_environment_systems(self): """初始化环境感知系统 - 修复后""" # 获取项目根目录 base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 修复:使用具体实现类 DefaultEnvironment self.environment = DefaultEnvironment(base_dir) self.logger.info("✅ 环境接口初始化完成") # 初始化智能家居环境 self.home = AIHome(base_dir) self.logger.info("✅ 智能家居环境初始化完成") # 修复:ActionExecutor 不需要参数 self.executor = ActionExecutor() self.logger.info("✅ 动作执行器初始化完成") # 新增:初始化环境接口(用于数据库和资源管理) self.env_interface = EnvironmentInterface(base_dir) self.logger.info("✅ 环境接口(数据库)初始化完成") # 记录环境状态 env_status = self.environment.get_system_info() self.logger.info(f"📊 系统状态: OS={env_status['os']}, CPU={env_status['cpu']}, " f"内存={env_status['memory']}GB, 磁盘={env_status['disk_usage']}%") def _initialize_subsystems(self): """初始化所有子系统""" # 1. 初始化模型管理器 from .model_manager import ModelManager self.model_manager = ModelManager( model_dir=system_config.MODEL_DIR, device=system_config.DEVICE, default_model=system_config.DEFAULT_MODEL ) self.logger.info("✅ 模型管理器初始化完成") # 2. 初始化健康系统 from .health_system import HealthSystem self.health_system = HealthSystem(self) self.logger.info("✅ 健康系统初始化完成") # 3. 初始化记忆系统 from .memory_system import MemorySystem self.memory_system = MemorySystem(self) self.logger.info("✅ 记忆系统初始化完成") # 4. 初始化情感系统 from .affective_system import AffectiveSystem self.affective_system = AffectiveSystem(agent=self) self.logger.info("✅ 情感系统初始化完成") # 5. 初始化认知架构 from .cognitive_architecture import CognitiveArchitecture self.cognitive_architecture = CognitiveArchitecture(agent=self) self.logger.info("✅ 认知架构初始化完成") # 6. 初始化通信系统 from .communication_system import CommunicationSystem self.communication_system = CommunicationSystem( cognitive_system=self.cognitive_architecture, agent=self # 传递智能体实例 ) self.logger.info("✅ 通信系统初始化完成") def process_input(self, user_input, user_id="default"): """处理用户输入(通过通信系统)""" return self.communication_system.process_input(user_input, user_id) def run_periodic_tasks(self): """运行周期性任务""" # 更新健康状态 self.health_system.update() # 情感系统更新 self.affective_system.grow() # 记忆系统维护 self.memory_system.consolidate_memories() # 修复:环境状态监控 - 使用时间戳 current_time = time.time() if not hasattr(self, "_last_env_check"): self._last_env_check = current_time # 每5分钟检查一次 if current_time - self._last_env_check > 300: self._last_env_check = current_time self._monitor_environment() def _monitor_environment(self): """监控环境状态 - 修复后""" try: # 获取当前系统状态 env_status = self.environment.get_system_info() # 安全解析磁盘使用率 disk_str = env_status.get('disk_usage', '0%').strip() if disk_str.endswith('%'): try: disk_usage = float(disk_str[:-1]) except ValueError: disk_usage = 0.0 else: disk_usage = 0.0 if disk_usage > 90: self.logger.warning(f"⚠️ 磁盘空间不足!当前使用率: {disk_usage}%") # 安全解析内存使用 memory_str = env_status.get('memory', '0GB/0GB') try: # 支持多种格式: "3.2GB/16GB" 或 "3.2/16.0 GB" parts = memory_str.replace('GB', '').replace(' ', '').split('/') if len(parts) >= 2: memory_used = float(parts[0]) memory_total = float(parts[1]) memory_ratio = memory_used / memory_total if memory_ratio > 0.85: self.logger.warning( f"⚠️ 内存使用过高!已用: {memory_used:.1f}GB, " f"总共: {memory_total:.1f}GB, " f"使用率: {memory_ratio * 100:.1f}%" ) except (ValueError, TypeError, ZeroDivisionError) as e: self.logger.error(f"内存数据解析失败: {memory_str} - {str(e)}") # 记录到健康系统 self.health_system.record_environment_status(env_status) except Exception as e: self.logger.error(f"环境监控失败: {str(e)}", exc_info=True) def get_status(self): """获取智能体状态报告""" # 获取基础状态 status = { "health": self.health_system.get_status(), "affective": self.affective_system.get_state(), "memory_stats": self.memory_system.get_stats(), "model": self.model_manager.get_current_model_info() } # 添加环境信息 try: env_status = self.environment.get_system_info() status["environment"] = { "os": env_status.get("os", "未知"), "cpu": env_status.get("cpu", "0%"), "memory": env_status.get("memory", "0GB/0GB"), "disk": env_status.get("disk_usage", "0%") } except Exception as e: status["environment"] = {"error": str(e)} return status # 环境交互方法 def explore_environment(self, path=None): """探索环境目录""" try: return self.environment.explore_directory(path) except Exception as e: self.logger.error(f"环境探索失败: {str(e)}") return {"error": str(e)} def execute_action(self, action, parameters): """通过执行器执行动作""" try: result = self.executor.execute(action, parameters) self.logger.info(f"执行动作: {action} {parameters} → {result.get('status', '未知')}") return result except Exception as e: self.logger.error(f"动作执行失败: {action} {parameters} - {str(e)}") return {"status": "error", "message": str(e)} ”没找到你说的agent_controller.py,只看见agent_core.py:“from agent.cognitive_architecture import CognitiveArchitecture from .model_manager import ModelManager from .memory_system import MemorySystem from .knowledge_manager import KnowledgeManager from .decision_system import DecisionSystem from .affective_system import AffectiveSystem from .health_system import HealthSystem from .environment_interface import EnvironmentInterface from .communication_system import CommunicationSystem class AgentCore: def __init__(self, config): self.config = config self.model_manager = ModelManager(config) self.memory = MemorySystem(config) self.knowledge = KnowledgeManager(config, self.memory) self.cognition = CognitiveArchitecture(config, self.model_manager) self.affect = AffectiveSystem(config) self.decision = DecisionSystem(config, self.cognition, self.affect) self.environment = EnvironmentInterface(config) self.communication = CommunicationSystem(config) self.health = HealthSystem(config) self.initialized = False def initialize(self): """初始化所有核心组件""" if self.initialized: return True try: # 加载默认模型 self.model_manager.load_model(self.config.DEFAULT_MODEL) # 初始化认知架构 self.cognition.initialize() # 加载环境接口 self.environment.load_environment() # 启动健康监测 self.health.start_monitoring() self.initialized = True return True except Exception as e: print(f"❌ 智能体初始化失败: {str(e)}") return False def process_input(self, input_data): """处理输入数据""" if not self.initialized: return {"error": "Agent not initialized"} # 认知处理 processed = self.cognition.process_input(input_data) # 情感评估 affective_response = self.affect.evaluate(processed) # 决策生成 decision = self.decision.make_decision(processed, affective_response) # 执行行动 result = self.environment.execute_action(decision) # 更新记忆 self.memory.store_experience({ "input": input_data, "processed": processed, "decision": decision, "result": result }) return result”
08-10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值