【问题标题】:Converting a system command to python for file search and delete将系统命令转换为 python 以进行文件搜索和删除
【发布时间】:2012-08-15 09:17:33
【问题描述】:

我有一个 cron 作业,它使用以下命令根据文件的年龄删除文件:

find /path/to/file/ -type f -mmin +120|xargs -I file rm 'file'

但是我想将该命令集成到一个 python 脚本中,该脚本涉及该任务以及其他也在 cron 上运行的东西。

我知道我可以将命令按原样插入 Python 脚本中,它可能会运行 find,但是我很想知道是否有更以 Python 为中心的方式来完成此任务以及它可能带来哪些其他好处?

【问题讨论】:

    标签: python find


    【解决方案1】:

    我的方法是:

    import os
    import time
    
    def checkfile(filename):
        filestats = os.stat(filename) # Gets infromation on file.
        if time.time() - filestats.st_mtime > 120: # Compares if file modification date is more than 120 less than the current time.
            os.remove(filename) # Removes file if it needs to be removed.
    
    path = '/path/to/folder'
    
    dirList = os.listdir(path) # Lists specified directory.
    for filename in dirList:
        checkfile(os.path.join(path, filename)) # Runs checkfile function.
    

    编辑:我测试了它,它没有工作,所以我修复了代码,我可以确认它工作。

    【讨论】:

    • 您应该使用os.path.join() 来构造路径名,而不是与“/”连接。
    • @silvado 谢谢 :) 我现在会添加它。建议的编辑也可以。
    【解决方案2】:

    使用os.popen()

    >>>os.popen("find /path/to/file/ -type f -mmin +120|xargs -I file rm 'file'")
    

    或者您可以使用subprocess 模块:

    >>> from subprocess import Popen, PIPE
    >>> stdout= Popen(['ls','-l'], shell=False, stdout=PIPE).communicate()
    >>> print(stdout)
    

    【讨论】:

      猜你喜欢
      • 2016-03-29
      • 1970-01-01
      • 1970-01-01
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 2018-05-23
      • 2014-05-21
      相关资源
      最近更新 更多