File size: 1,502 Bytes
64fbfae
bfccab8
 
3fe81b3
 
a5cad2a
 
 
 
bfccab8
d0744fa
bfccab8
d0744fa
 
 
 
 
 
f505e89
bfccab8
 
 
f505e89
d0744fa
 
 
 
 
 
 
 
 
 
 
 
 
a5cad2a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import subprocess
import sys
import logging
import os

# 获取当前脚本所在的目录
script_dir = os.path.dirname(os.path.realpath(__file__))
log_file = os.path.join(script_dir, "logs.txt")

# 配置日志
logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 创建一个将输出同时发送到控制台和日志文件的处理程序
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
logging.getLogger().addHandler(console_handler)

# 重定向标准输出和标准错误到日志文件和控制台
sys.stdout = logging.getLogger().handlers[0].stream
sys.stderr = logging.getLogger().handlers[0].stream

try:
    # 在try块中运行v2_3.py,并将输出重定向到日志文件
    with open(log_file, 'a') as log_file_handle:
        subprocess.run(['python', 'v2_3.py'], check=True, stdout=log_file_handle, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
    # 捕获异常并记录到日志文件
    logging.exception(f"程序发生异常: {e}")
except Exception as e:
    # 捕获其他异常并记录到日志文件
    logging.exception(f"程序发生异常: {e}")
finally:
    # 最后,关闭日志处理程序,以确保所有日志都被写入到日志文件
    logging.getLogger().removeHandler(console_handler)
    console_handler.close()