Python 2.7中匹配日期时间的通配符或*

0 投票
1 回答
892 浏览
提问于 2025-04-18 01:53

我正在尝试匹配以下字符串,但一直没有成功。下面是我的尝试。

LOG FORMAT: 
riskserver.2014-04-07-08:45:01.log

我觉得我只需要年份、月份和日期。所以我尝试使用通配符 *,但 Python 2.7 似乎不太喜欢这个。

cmd = 'tail -n10000 /opt/rubedo/log/riskserver.'+nowFormat+*'

在这里非常感谢大家的帮助。谢谢,我希望我解释得清楚,能让一些人理解。

我正在使用 subprocess,并且涉及到 grep。

tail: cannot open `/opt/rubedo/log/riskserver.2014-04-08' for reading: No such file or directory

grep: not: 没有这样的文件或目录

EDIT:
now = datetime.datetime.now().strftime("%H:%M:%S")
nowFormat = datetime.datetime.now().strftime("%Y\-%m\-%d")

1 个回答

0

glob 就是一个通配符,通常用星号(*)表示,比如说 ls *.txt 这个命令会被 Linux 的命令行处理成 ls f1.txt f2.txt f3.txt f4.txt ... 这样的形式。

也就是说,ls 实际上接收到的是一个文件列表,这些文件名是符合条件的,而不是直接接收那个匹配的字符串。这就是评论里提到的意思。

nowFormat = "2014-04-07"
cmd = 'tail -n10000 /opt/rubedo/log/riskserver.'+nowFormat+'*'
os.system(cmd) #this will execute it through your linux shell you should see the output, allthough this call will not give you access to the output in python

在 Python 中也是类似的用法。

import glob
fnames = glob.glob('/opt/rubedo/log/riskserver.'+nowFormat+'*')
print fnames

撰写回答