首页 > 解决方案 > 如何将我的 shell 扫描脚本嵌入到 Python 脚本中?

问题描述

我一直在使用以下 shell 命令从名为 scanner_name 的扫描仪中读取图像并将其保存在名为 file_name 的文件中

scanimage -d <scanner_name> --resolution=300 --format=tiff --mode=Color 2>&1 > <file_name>

这对我的目的来说效果很好。我现在正试图将它嵌入到 python 脚本中。我需要像以前一样将扫描的图像保存到文件中,并将任何标准输出(比如错误消息)捕获到字符串中

我试过了

    scan_result = os.system('scanimage -d {} --resolution=300 --format=tiff --mode=Color 2>&1 > {} '.format(scanner, file_name))

但是当我在一个循环中运行它(使用不同的扫描仪)时,扫描之间存在不合理的长时间延迟,并且直到下一次扫描开始时才保存图像(文件被创建为空文件并且直到下一次才被填充扫描命令)。所有这些都使用scan_result=0,即表示没有错误

已经向我建议了子流程方法 run(),我已经尝试过

with open(file_name, 'w') as scanfile:

    input_params = '-d {} --resolution=300 --format=tiff --mode=Color 2>&1 > {} '.format(scanner, file_name)
    scan_result = subprocess.run(["scanimage", input_params], stdout=scanfile, shell=True)

但这以某种不可读的文件格式保存了图像

关于可能出了什么问题的任何想法?或者我还能尝试什么来让我既保存文件又检查成功状态?

标签: pythonshellscanning

解决方案


subprocess.run()绝对是首选,os.system()但它们都不支持并行运行多个作业。您将需要使用类似 Python 的库之类的东西来并行运行多个任务(或者在基本APImultiprocessing之上痛苦地自己重新实现它)。subprocess.Popen()

您对如何运行也有一个基本的误解subprocess.run()。您可以传入一个字符串shell=True或一个标记列表和shell=False(或根本没有shell关键字;False这是默认值)。

with_shell = subprocess.run(
    "scanimage -d {} --resolution=300 --format=tiff --mode=Color 2>&1 > {} ".format(
        scanner, file_name), shell=True)

with open(file_name) as write_handle:
    no_shell = subprocess.run([
        "scanimage", "-d", scanner, "--resolution=300", "--format=tiff",
            "--mode=Color"],  stdout=write_handle)

您会注意到后者不支持重定向(因为这是一个 shell 功能),但这在 Python 中相当容易实现。(我去掉了标准错误的重定向——你真的希望错误消息保留在 stderr 上!)

如果您有一个更大的工作 Python 程序,那么与multiprocessing.Pool(). 如果这是一个小型的独立程序,我建议您完全剥离 Python 层并使用类似xargsGNU的东西parallel来运行数量上限的并行子进程。


推荐阅读