Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 循环打印_Python_Linux_Python 3.x - Fatal编程技术网

Python 循环打印

Python 循环打印,python,linux,python-3.x,Python,Linux,Python 3.x,我有以下代码要打印到系统默认打印机: def打印文件(文件): 打印(“打印文件…”) 以open(文件“rb”)作为源: printer=subprocess.Popen('/usr/bin/lpr',stdin=subprocess.PIPE) printer.stdin.write(source.read()) 如果我单独使用这个函数,它会工作得很好。但是如果在这样的循环构造中使用它: 为True时: 打印文件(文件) (...) 打印作业将不会运行(尽管)循环将继续,不会出现错误 我

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

def打印文件(文件):
打印(“打印文件…”)
以open(文件“rb”)作为源:
printer=subprocess.Popen('/usr/bin/lpr',stdin=subprocess.PIPE)
printer.stdin.write(source.read())
如果我单独使用这个函数,它会工作得很好。但是如果在这样的循环构造中使用它:

为True时:
打印文件(文件)
(...)
打印作业将不会运行(尽管)循环将继续,不会出现错误

我试图建立一个时间延迟,但它没有帮助


[编辑]:进一步的调查表明,打印功能(从循环调用时)将暂停打印作业…?

在现代Python 3中,建议在大多数情况下使用
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
在这里有一些缺点

  • 使用
    Popen.stdin
    可能会产生死锁,如果它超出了OS管道缓冲区(根据Python文档)
  • 由于没有等待
    Popen
    进程完成
    wait()
  • 根据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
    
    可以一次打印一个文件或一堆文件