【问题标题】:printing out a text file with default printer [duplicate]使用默认打印机打印出文本文件[重复]
【发布时间】:2016-09-13 15:07:26
【问题描述】:

对于我自己的一个小项目,我正在尝试编写一个程序,在计算机默认打印机上打印出文件的内容。 我知道周围有很多类似的问题,但它们都不适用于我的电脑(Linux mint 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'

有没有人知道锄头可以在 python 中实现这个?它真的不必在 Windows 上工作

问候

Cid-El

【问题讨论】:

  • 为什么是StringIO 而不是open
  • @Moses Koledoye 您的评论修复了这两个错误 :) 我在写答案的第二部分时意识到。
  • StringIO 的东西一开始也让检测重复变得更加困难。
  • 我只使用了我从谷歌得到的代码,所以不要问我为什么不打开大声笑

标签: python python-2.7 printing


【解决方案1】:

您不必为此使用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 读取标准输入并打印它(这仍然是一段有趣的代码:))

要打印文件的内容,您必须阅读它,在这种情况下,它会更简单,因为管道和文件可以立即一起工作:

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]

【讨论】:

  • 完美!非常感谢!!!!!!!!!
  • ps。如果我早点打开它,这甚至会打印出一个 pdf 文件!太棒了!
  • 很高兴能帮上忙。
猜你喜欢
  • 2014-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-01
  • 1970-01-01
相关资源
最近更新 更多