Python os.stat不在文件名中扩展通配符

时间:2016-03-19 18:43:47

标签: python

我正在做的事情可能真的很蠢,但有人可以帮忙。我要做的就是统计一个文件。 Python不会发生这种情况,当我调试我的python变量时,我可以在shell中使用它的输出进行统计。请参阅以下内容:

[root@logmaster output]# cat /usr/local/nagios/libexec/check_logrip_log_not_stale.py

import os
import sys
import datetime
import time

# Nagios return values
nagiosRetValOk       = 0
nagiosRetValWarn     = 1
nagiosRetValCritical = 2

# Below is the filename I am after
#logrip-out-2016-03-19-1458386101

dateFormat = datetime.datetime.now().strftime("%Y-%m-%d")
logFormat = "/home/famnet/logs/output/logrip-out-%s-*" % dateFormat


print os.stat(logFormat)

以下是运行基本脚本时发生的情况:

    [root@logmaster output]# python /usr/local/nagios/libexec/check_logrip_log_not_stale.py
    Traceback (most recent call last):
      File "/usr/local/nagios/libexec/check_logrip_log_not_stale.py", line 36, in <module>
        print os.stat(logFormat)
OSError: [Errno 2] No such file or directory: '/home/famnet/logs/output/logrip-out-2016-03-19-*'

如果这对某些专家来说很容易浪费时间,请原谅我。

谢谢, 但是,当我获取我的打印调试的输出并在shell中运行时,它可以工作。

[root@logmaster output]# stat /home/famnet/logs/output/logrip-out-2016-03-19-*
  File: `/home/famnet/logs/output/logrip-out-2016-03-19-1458386101'
  Size: 42374797        Blocks: 82776      IO Block: 4096   regular file
Device: fd02h/64770d    Inode: 36590817    Links: 1
Access: (0644/-rw-r--r--)  Uid: (  504/  famnet)   Gid: ( 1100/   staff)
Access: 2016-03-19 07:15:01.725794193 -0400
Modify: 2016-03-19 07:44:09.847793116 -0400
Change: 2016-03-19 07:44:09.847793116 -0400

2 个答案:

答案 0 :(得分:3)

扩展通配符是许多常见shell的一个特性,例如bash。它不是基于os.stat的系统调用的功能。

如果您想针对多个文件调用os.stat,则必须先列出它们(使用glob.glob之类的内容),然后每个路径调用os.stat一次。像这样:

for full_path in glob.glob(logFormat):
    print os.stat(full_path)

同样注意,带有通配符的路径可以扩展到多个具体路径,这些路径可以与命令行STAT(1)一起使用,但肯定会破坏os.stat,它只接受一个路径参数。

答案 1 :(得分:0)

os.stat无法自动展开通配符...尝试使用glob