Skip to main content
 首页 » 编程设计

python之获取最新修改的文件并作为输入传递给子流程

2025年05月04日10duanxz

我有代码打印激活运动时保存的图像快照的最新文件路径,我试图将此文件路径用作我代码的下一部分的输入,该代码将图像转换为仅保留蓝色 Blob 。感谢任何帮助,我是编码新手。

#!/bin/bash/python 
 
import os 
from subprocess import  check_call 
 
path = '/..' 
os.chdir(path) 
files = sorted(os.listdir(os.getcwd()), key=os.path.getmtime) 
 
newest = files[-1] 
if newest == "Thumbs.db": 
        'newest = files[-1] 
 
newest = [path+"/"+newest] 
a = newest 
 
print newest 
##### 转换为蓝色 Blob
check_call(["sudo","convert","imgIn.jpg", "-posterize","2","imgOut.jpg"]) 
 
check_call([ "sudo",'convert', 'imgIn.jpg', '-matte', '(', '+clone', '-fuzz',     57%', '-opaque', 'black', '-transparent', 'blue', ')', '-compose', 'DstOut', '-    composite', 'imgOut.jpg']) 

如何使用最新的文件路径作为imgIn.jpg?

请您参考如下方法:

编写一个名为 get_latest_file() 的函数:

from os.path import isabs, getmtime 
from os import getcwd, listdir, path 
 
 
def get_latest_file(p): 
    if not isabs(p): 
        p = path.join(getcwd(), p) 
    files = sorted([path.join(p, x) for x in listdir(p)], key=getmtime) 
    return (files and files[-1]) or None 

这将为您提供按修改时间排序的最新文件,并返回给定目录的最后/最新匹配文件。

注意:在上面的函数中需要注意的一点是,您需要为排序键 getmtime() 建立一个绝对路径列表才能正常工作否则它将抛出 OSError(s),因为 os.listdir() 为您提供给定目录中的“名称”列表作为相对名称。

示例:

get_latest_file("images") 

然后您可以将此结果传递给您的 check_output() 调用:

latest_image = get_latest_file("images") 
check_call(["sudo", "convert", latest_image, "-posterize", "2", "imgOut.jpg"]) 

更新:您可以然后通过编写一个名为 convert_image() 的函数来完成此操作,如下所示:

from os.path impomrt splitext 
from subprocess import check_call 
 
 
def convert_image(inf): 
    base, ext = splitext(inf) 
    outf = "{0:s}-converted{1:s}".format(base, ext) 
    check_call(["sudo", "convert", inf, "-posterize", "2", outf]) 

更新#2:在为 get_latest_file() 传递路径方面,您在这里可能有三种选择:

IMAGE_PATH = "/path/to/images"                   # hard coded 
 
image_path = raw_input("Enter path to image: ")  # prompt user 
 
image_path = sys.argv[1]                         # from the command line 

旁注:您的 Shebang不太对;它应该是:#!/usr/bin/env python

引用资料: