BBrother commited on
Commit
1b5bcb3
1 Parent(s): f3cc4f3

Update nologs.py

Browse files
Files changed (1) hide show
  1. nologs.py +21 -23
nologs.py CHANGED
@@ -1,30 +1,28 @@
1
- import os
2
  import subprocess
3
  import logging
4
 
5
- # 删除已存在的 logs.txt 文件
6
- if os.path.exists("logs.txt"):
7
- os.remove("logs.txt")
8
 
9
- # 配置 logging,将日志同时输出到文件 logs.txt
10
- logging.basicConfig(
11
- level=logging.INFO,
12
- format="%(asctime)s - %(levelname)s - %(message)s",
13
- filename="logs.txt",
14
- filemode="w",
15
- )
16
 
17
- try:
18
- # 执行您的 Python 程序并将标准输出和标准错误都重定向到 subprocess.DEVNULL
19
- with open(os.devnull, 'w') as null:
20
- proc = subprocess.Popen(
21
- ['python', 'v2_3.py'],
22
- stdout=null, stderr=subprocess.STDOUT
23
- )
 
 
 
 
 
 
24
 
25
- # 等待程序执行完成
26
- proc.wait()
27
 
28
- except Exception as e:
29
- # 记录异常信息
30
- logging.error(f"程序发生异常: {e}")
 
 
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()