【发布时间】:2019-10-28 08:56:13
【问题描述】:
我一直在使用以下 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)
但这会将图像保存为某种不可读的文件格式
关于可能出现什么问题的任何想法?或者我还可以尝试什么来保存文件并检查成功状态?
【问题讨论】:
-
你不能使用
subprocess.run([... list ...], shell=True),它要么用shell=True传递一个单一的sting,要么传递一个没有shell的令牌列表。