gpt4 book ai didi

python - 循环打印

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:42 25 4
gpt4 key购买 nike

我有以下代码打印到系统默认打印机:

def printFile(file):
print("printing file...")
with open(file, "rb") as source:
printer = subprocess.Popen('/usr/bin/lpr', stdin=subprocess.PIPE)
printer.stdin.write(source.read())

如果我单独使用这个函数,它会很好用。但是如果在这样的循环结构中使用它:

while True:
printFile(file)
(...)

打印作业不会运行(虽然)循环将继续而不会出现错误...

我试图延迟构建,但没有帮助...

[编辑]:进一步的调查显示打印功能(当从循环中调用时)将暂停打印作业......?

最佳答案

在现代Python3中,大多数情况下建议使用subprocess.run(),而不是直接使用subprocess.Popen。我会将它留给 lpr 来读取文件,而不是将其传递给标准输入:

def printFile(file):
print("printing file...")
cp = subprocess.run(['\usr\bin\lpr', file])
return cp.returncode

使用 subprocess.run 可以让您确定 lpr 进程是否正确完成。这样您就不必读取和写入完整的文件。 lpr 完成后,您甚至可以删除该文件。

直接使用Popen在这里有一些缺点;

  1. 使用 Popen.stdin 如果溢出操作系统管道缓冲区(根据 Python 文档)可能会产生死锁。
  2. 由于您没有wait() 等待Popen 进程完成,因此您不知道它是否完成且没有错误。

根据 lpr 的设置方式,它可能有速率控制。也就是说,如果它在短时间内收到大量打印请求,它可能会停止打印。

编辑:我刚刚想到了一些事情。大多数 lpr 实现允许您一次打印多个文件。所以你也可以这样做:

def printFile(files):
"""
Print file(s).

Arguments:
files: string or sequence of strings.
"""
if isinstance(files, str):
files = [files]
# if you want to be super strict...
if not isinstance(files (list, tuple)):
raise ValueError('files must be a sequence type')
else:
if not all(isinstance(f, str) for f in files):
raise ValueError('files must be a sequence of strings')
cp = subprocess.run(['\usr\bin\lpr'] + files)
return cp.returncode

这会一次打印一个文件或一大堆...

关于python - 循环打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57308692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com