BBrother commited on
Commit
0d9a9a6
1 Parent(s): 1b5bcb3

Update nologs.py

Browse files
Files changed (1) hide show
  1. nologs.py +31 -21
nologs.py CHANGED
@@ -1,28 +1,38 @@
1
  import subprocess
 
2
  import logging
 
3
 
4
- # 配置日志
5
- logging.basicConfig(filename='logs.txt', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
 
 
6
 
7
- # 执行程序并将标准输出和标准错误重定向到日志
8
- proc = subprocess.Popen(['python', 'v2_3.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
9
 
10
- # 读取并记录标准输出和标准错误
11
- while True:
12
- output = proc.stdout.readline()
13
- error = proc.stderr.readline()
14
-
15
- if not output and not error:
16
- break
17
-
18
- if output:
19
- logging.info(output.strip())
20
-
21
- if error:
22
- logging.error(error.strip())
23
 
24
- # 等待程序执行完成
25
- proc.wait()
 
26
 
27
- # 关闭日志处理程序
28
- logging.shutdown()
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import subprocess
2
+ import sys
3
  import logging
4
+ import os
5
 
6
+ # 检查是否存在 logs.txt 文件,如果存在则删除它
7
+ log_file = '/content/logs.txt'
8
+ if os.path.exists(log_file):
9
+ os.remove(log_file)
10
 
11
+ # 配置日志
12
+ logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
13
 
14
+ # 创建一个将输出同时发送到控制台和日志文件的处理程序
15
+ console_handler = logging.StreamHandler(sys.stdout)
16
+ console_handler.setLevel(logging.INFO)
17
+ formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
18
+ console_handler.setFormatter(formatter)
19
+ logging.getLogger().addHandler(console_handler)
 
 
 
 
 
 
 
20
 
21
+ # 重定向标准输出和标准错误到日志文件和控制台
22
+ sys.stdout = logging.getLogger().handlers[0].stream
23
+ sys.stderr = logging.getLogger().handlers[0].stream
24
 
25
+ try:
26
+ # 在try块中运行sd_clsa_webui_colab_ipynb_v2_3.py,并将输出重定向到日志文件
27
+ with open(log_file, 'a') as log_file_handle:
28
+ subprocess.run(['python', 'sd_clsa_webui_colab_ipynb_v2_3.py'], check=True, stdout=log_file_handle, stderr=subprocess.STDOUT)
29
+ except subprocess.CalledProcessError as e:
30
+ # 捕获异常并记录到日志文件
31
+ logging.exception(f"程序发生异常: {e}")
32
+ except Exception as e:
33
+ # 捕获其他异常并记录到日志文件
34
+ logging.exception(f"程序发生异常: {e}")
35
+ finally:
36
+ # 最后,关闭日志处理程序,以确保所有日志都被写入到日志文件
37
+ logging.getLogger().removeHandler(console_handler)
38
+ console_handler.close()