代码之家  ›  专栏  ›  技术社区  ›  unmounted

如何在纯Python中表达此Bash命令

  •  1
  • unmounted  · 技术社区  · 17 年前

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

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

    我熟悉os.name和getpass.getuser中最通用的跨平台元素。我还可以使用此函数生成~/podcast/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
    

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

    4 回复  |  直到 16 年前
        1
  •  5
  •   wnoise    17 年前
    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))
    
        2
  •  3
  •   nosklo    17 年前
    import subprocess
    subprocess.call(['find', '~/podcasts/current', '-mindepth', '2', '-mtime', '+5',
                     '-exec', 'mv', '{}', '~/podcasts/old', ';'], shell=True)
    

    那不是玩笑。这个python脚本将完全执行bash one所做的操作。

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

        3
  •  2
  •   John Millikin    17 年前

    这不是Bash命令,而是 find 发现

        4
  •  0
  •   William Keller    17 年前
    import os, stat
    os.stat("test")[stat.ST_MTIME]
    

    我会给你时间的。我建议把它们固定在墙上 walk_results[2] ,然后递归,为中的每个dir调用函数 walk_results[1]