BBrother commited on
Commit
dfda5a5
1 Parent(s): 060c5b8

Update nologs.py

Browse files
Files changed (1) hide show
  1. nologs.py +17 -23
nologs.py CHANGED
@@ -1,27 +1,21 @@
1
  import subprocess
2
- import os
3
 
4
- # 打开一个日志文件以追加方式写入
5
- log_file = open("logs.txt", "a")
 
 
 
6
 
7
- # 执行您的Python程序并将标准输出和标准错误重定向到subprocess.PIPE
8
- proc = subprocess.Popen(['python', 'v2_3.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1)
 
9
 
10
- # 逐行处理程序的输出
11
- for line in iter(proc.stdout.readline, ''):
12
- # 处理输出
13
- log_file.write(line)
14
- log_file.flush() # 立即将数据刷新到文件,以确保实时记录
15
-
16
- # 等待程序执行完成
17
- proc.wait()
18
-
19
- # 关闭日志文件
20
- log_file.close()
21
-
22
- # 获取程序的返回码
23
- return_code = proc.returncode
24
-
25
- # 如果程序返回非零退出码,打印错误信息
26
- if return_code != 0:
27
- print(f"程序返回非零退出码: {return_code}")
 
1
  import subprocess
 
2
 
3
+ # 如果当前目录下有"logs.txt"文件,先删除它
4
+ try:
5
+ os.remove("logs.txt")
6
+ except FileNotFoundError:
7
+ pass
8
 
9
+ with open("logs.txt", "w") as log_file:
10
+ # 执行您的Python程序,将标准输出和标准错误重定向到/dev/null
11
+ proc = subprocess.Popen(['python', 'v2_3.py'], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
12
 
13
+ # 循环读取标准输出并写入日志文件
14
+ while True:
15
+ output = proc.stdout.readline()
16
+ if not output:
17
+ break
18
+ log_file.write(output.decode("utf-8"))
19
+
20
+ # 等待程序执行完成
21
+ proc.wait()