【问题标题】:How to express this Bash command in pure Python如何在纯 Python 中表达这个 Bash 命令
【发布时间】:2008-09-23 01:15:54
【问题描述】:

我在一个有用的 Bash 脚本中有这一行,但我还没有设法将其翻译成 Python,其中“a”是用户输入的要归档的文件的天数:

find ~/podcasts/current -mindepth 2 -mtime '+`a`+' -exec mv {} ~/podcasts/old \;

我熟悉最通用的跨平台元素的 os.name 和 getpass.getuser。我也有这个函数来生成所有文件的全名列表,相当于 ~/podcasts/current:

def AllFiles(filepath, depth=1, flist=[]):
    fpath=os.walk(filepath)
    fpath=[item for item in fpath]
    while depth < len(fpath):
        for item in fpath[depth][-1]:
            flist.append(fpath[depth][0]+os.sep+item)
        depth+=1
    return flist

首先,必须有更好的方法来做到这一点,欢迎提出任何建议。无论哪种方式,例如,“AllFiles('/users/me/music/itunes/itunes music/podcasts')”都会在 Windows 上给出相关列表。大概我应该能够检查这个列表并调用 os.stat(list_member).st_mtime 并将所有超过某个天数的东西移到存档中;我有点卡在那个位上。

当然,任何带有 bash 命令简洁的东西也会很有启发性。

【问题讨论】:

    标签: python shell language-comparisons


    【解决方案1】:
    import os
    import shutil
    from os import path
    from os.path import join, getmtime
    from time import time
    
    archive = "bak"
    current = "cur"
    
    def archive_old_versions(days = 3):
        for root, dirs, files in os.walk(current):
            for name in files:
                fullname = join(root, name)
                if (getmtime(fullname) < time() - days * 60 * 60 * 24):
                    shutil.move(fullname, join(archive, name))
    

    【讨论】:

    • 要获取文件的 mtime,请使用 os.path.getmtime(fullname) 而不是 os.stat(fullname).st_mtime
    • 您可以使用 shutil.move 进行移动。如果源和目标在同一个文件系统上,则默认为 os.rename,或者进行复制/删除。
    【解决方案2】:
    import subprocess
    subprocess.call(['find', '~/podcasts/current', '-mindepth', '2', '-mtime', '+5',
                     '-exec', 'mv', '{}', '~/podcasts/old', ';'], shell=True)
    

    这不是开玩笑。这个 python 脚本将完全按照 bash 的方式执行。

    编辑:删除最后一个参数的反斜杠,因为它不需要。

    【讨论】:

    • 你不需要';'前面的反斜杠在 Python 中。
    • @Glyph:你是对的。对于 nosklo 来说幸运的是,反斜杠将被 python 消耗(在这种情况下实际上被忽略)。
    【解决方案3】:

    这不是 Bash 命令,而是find 命令。如果你真的想把它移植到 Python 上,这是可能的,但你永远无法编写出如此简洁的 Python 版本。 find 经过 20 多年的优化,在处理文件系统方面表现出色,而 Python 是一种通用编程语言。

    【讨论】:

      【解决方案4】:
      import os, stat
      os.stat("test")[stat.ST_MTIME]
      

      会给你mtime。我建议修复walk_results[2] 中的那些,然后递归调用walk_results[1] 中每个目录的函数。

      【讨论】:

      • 您实际上可以像这样引用 mtime:os.stat('test').st_mtime - 它消除了导入 stat 模块的需要。
      猜你喜欢
      • 2012-09-25
      • 1970-01-01
      • 2010-10-11
      • 2020-04-04
      • 1970-01-01
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多