使用默认打印机打印出文本文件

时间:2016-09-13 15:07:26

标签: python python-2.7 printing

对于我自己的一个小项目,我正在尝试编写一个程序,在计算机默认打印机上打印出文件的内容。 我知道周围有很多类似的问题,但它们都不能在我的电脑上运行(Linux模板17.3)

这是我试过的一个,它最接近我需要的东西:

from subprocess import Popen
from cStringIO import StringIO

# place the output in a file like object
sio = StringIO("test.txt")

# call the system's lpr command
p = Popen(["lpr"], stdin=sio, shell=True)
output = p.communicate()[0]

这给了我以下错误:

Traceback (most recent call last):
  File "/home/vandeventer/x.py", line 8, in <module>
    p = Popen(["lpr"], stdin=sio, shell=True)
  File "/usr/lib/python2.7/subprocess.py", line 702, in __init__
    errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)
  File "/usr/lib/python2.7/subprocess.py", line 1117, in _get_handles
    p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'

Doe有谁知道锄头可以在python中实现这个吗?它真的没有在Windows上工作

此致

西德的EL

1 个答案:

答案 0 :(得分:2)

您不必使用StringIO。只需使用subprocess的管道功能,并将数据写入p.stdin

from subprocess import Popen
# call the system's lpr command
p = Popen(["lpr"], stdin=subprocess.PIPE, shell=True)  # not sure you need shell=True for a simple command
p.stdin.write("test.txt")
output = p.communicate()[0]

作为奖励,这符合Python 3(StringIO已重命名,因为:))

但是:这只会打印一个包含一行的大白页:test.txtlpr读取标准输入并打印它(这仍然是一段有趣的代码:))

要打印文件的内容,您必须阅读它,在这种情况下,它甚至更简单,因为管道&amp;文件一起工作:

from subprocess import Popen
with open("test.txt") as f:
  # call the system's lpr command
  p = Popen(["lpr"], stdin=f, shell=True)  # not sure you need shell=True for a simple command
  output = p.communicate()[0]