如何在纯Python中表达此Bash命令
时间:2020-03-06 14:34:32 来源:igfitidea点击:
我在有用的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
首先,必须有更好的方法来做到这一点,欢迎任何建议。无论哪种方式,例如,在Windows上," AllFiles('/ users / me / music / itunes / itunes music / podcasts')"都会给出相关列表。大概我应该能够遍历此列表,并调用os.stat(list_member).st_mtime,并将所有超过特定天数的东西移至存档中;我有点卡住了。
当然,只要执行bash命令,任何事情都将得到启发。
解决方案
那不是Bash命令,而是一个find
命令。如果我们确实想将其移植到Python,则可以,但是我们永远无法编写出如此简洁的Python版本。 " find"经过20多年的优化,在处理文件系统方面表现出色,而Python是一种通用的编程语言。
import os, stat os.stat("test")[stat.ST_MTIME]
会给你mtime的。我建议将其固定在" walk_results [2]"中,然后递归,为" walk_results [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))
import subprocess subprocess.call(['find', '~/podcasts/current', '-mindepth', '2', '-mtime', '+5', '-exec', 'mv', '{}', '~/podcasts/old', ';'], shell=True)
那不是开玩笑。这个python脚本将完全执行bash的操作。
编辑:因为不需要它,所以在最后一个参数上删除了反斜杠。