我有一个场景,我想将多个文件的日志重定向到同一个符号链接(symbolic link)。
我假设三个文件 file1.log
file2.log
和 file3.log
file1.log
有
This is file 1
file2.log
有This is file 2
file3.log
有This is file 3
现在我想创建所有这个文件的符号链接(symbolic link)到 file.log
使得 file.log
的内容是This is file 1
This is file 2
This is file 3
这是动态发生的。即如果file1.log
的内容然后修改例如 This line append to file1.log
然后 file1.log
应该显示This is file 1
This is file 2
This is file 3
This line append to file1.log
有没有这样做的标准方法?我已经在这里停留了很长一段时间。我正在使用
ubuntu 18.04
和 python 3.6.9
- - - - - - - - - - - - - - -编辑 - - - - - - - - - - ---------------这不是我拥有的所有文件,例如 20 个名称为
file*.log
的文件并且可以有多个文件,如 f1X.log
f2X.log
需要重定向到f1.log
, f2.log
最佳答案
from itertools import chain
from pathlib import Path
from time import sleep
log_path_list = [p for p in Path('.').glob('*.log') if p.name != 'file.log']
log = Path('file.log')
files = []
for log_path in log_path_list:
files.append(log_path.open())
lines = chain(*map(lambda f: (line for line in f),files))
with log.open('w') as flog:
for line in lines:
flog.write(line)
flog.flush()
try:
while True:
oneline = ""
for f in files:
f.seek(0, 2)
oneline = f.readline()
if not oneline:
continue
flog.write(oneline)
if oneline:
flog.flush()
else:
sleep(0.3)
except Exception as e:
print(e)
for f in files:
f.close()
这不是符号链接(symbolic link),但它会将所有日志文件中的所有内容输出到file.log
然后将任何新行追加到 file.log
.只要
file.log
,python 进程就应该在那里停留。需要有更新。我不认为这是一个聪明的解决方案,但如果这是你的唯一方法,那么你就有了一个解决方案的开始。
关于python - 多个文件到单个文件的符号链接(symbolic link),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64747305/