python - 使用默认打印机打印文本文件

标签 python python-2.7 printing

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

关于python - 使用默认打印机打印文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39473347/

相关文章:

python - 将 if-then 语句应用于多列并输出到新列 - Pandas

python - 将字符串文件转换为所需格式 : replace/with _ except the ones before comma

cocoa - 打印CAL层

css - IE Print 从底部删除段落

python-2.7 - 在numpy中使用python数值求解器求解方程

python - 在逗号前打印 2 个数字

python - 导入错误 : DLL load failed: not a valid Win32 application

python - 如何将相关矩阵绘制为一组椭圆,类似于 R 露天包?

python - pandas 仅在两侧都存在值时才进行插值

Python:转换为字符串时如何近似 float ?