Python - 为目录中的所有文件运行bash脚本

0 投票
6 回答
4377 浏览
提问于 2025-04-16 16:55

我正在创建一个Python脚本,用来处理一些常见的图像相关任务,但在某个部分遇到了困难:

有一个人写的Bash脚本,用于ImageMagick,链接在这里: http://www.fmwconcepts.com/imagemagick/autocolor/index.php

这个脚本基本上只能处理单个文件(我不能把*.jpg传给它,因为这样会出错),否则我就不会遇到这个问题了。所以我需要用Python对每个文件运行这一行命令:

~/autocolor.sh -m " + ColorMethod + " -c " + WorkingDirectory + InputFileName + " " + WorkingDirectory + OutputFileName

这是我目前的代码块:

elif RetouchOption == "04":
    ColorMethod = input("What method will you use (options are gamma, recolor, none)?: ")
    ClipMode = input("What clipping mode will you use (options are together or separate)?: ")
    for f in WorkingDirectory + "*.jpg":
        do
        os.system("sh ~/autocolor.sh -m " + ColorMethod + " -c " + WorkingDirectory + FileName + " " + WorkingDirectory + FileName)

WorkingDirectory已经被定义为一个变量,而ColorMethod和ClipMode也在这个代码块中定义。我需要做的是获取一个FileName变量(或者其他方法让这段代码能正常工作)。

谢谢你的帮助!如果我提供的信息不够,请告诉我。我听说os.system不是做这种事情的最佳方式,但到目前为止,它在执行我脚本中的其他命令时效果很好,所以我会在以后再考虑改进这部分。

6 个回答

0

你有没有想过用 os.listdir 这个方法来获取文件夹里的所有文件呢?

一旦你得到了文件夹里所有文件的列表,就可以找出所有的JPG文件,然后用下面的代码把文件名最后的“.jpg”去掉:

>>> f = 'firstPic.jpg'
>>> f. replace(".jpg", '')
'firstPic'

希望这对你有帮助

1

难道用bash不是更好吗?

for f in *.jpg; do ./autocolor.sh $f; done

1

这里有一些想法:

from glob import glob
import subprocess

elif RetouchOption == "04":
    ColorMethod = input("What method will you use (options are gamma, recolor, none)?: ")
    ClipMode = input("What clipping mode will you use (options are together or separate)?: ")
    script = ["sh", "~/autocolor.sh"]
    method = "-m %s" % ColorMethod
    clipmode = "-c %s" % ClipMode
    for filename in glob("*.jpg"):
        subprocess.call(script + [method, clipmode, filename, filename])

glob 非常好用,而 subprocess 比 os.system 更受欢迎,正如你所猜测的那样。

需要注意的是,如果不指定你的工作目录,glob 会使用“脚本的当前工作目录”。如果你想让它使用工作目录,可以试试下面的方式:

import os

for filename in glob(os.path.join(WorkingDirectory, '*.jpg')):
    ...

撰写回答