Skip to content
Advertisement

Using cat command in Python for printing

In the Linux kernel, I can send a file to the printer using the following command

cat file.txt > /dev/usb/lp0

From what I understand, this redirects the contents in file.txt into the printing location. I tried using the following command

>>os.system('cat file.txt > /dev/usb/lp0') 

I thought this command would achieve the same thing, but it gave me a “Permission Denied” error. In the command line, I would run the following command prior to concatenating.

sudo chown root:lpadmin /dev/usb/lp0

Is there a better way to do this?

Advertisement

Answer

While there’s no reason your code shouldn’t work, this probably isn’t the way you want to do this. If you just want to run shell commands, bash is much better than python. On the other hand, if you want to use Python, there are better ways to copy files than shell redirection.

The simplest way to copy one file to another is to use shutil:

shutil.copyfile('file.txt', '/dev/usb/lp0')

(Of course if you have permissions problems that prevent redirect from working, you’ll have the same permissions problems with copying.)


You want a program that reads input from the keyboard, and when it gets a certain input, it prints a certain file. That’s easy:

import shutil

while True:
    line = raw_input() # or just input() if you're on Python 3.x
    if line == 'certain input':
        shutil.copyfile('file.txt', '/dev/usb/lp0')

Obviously a real program will be a bit more complex—it’ll do different things with different commands, and maybe take arguments that tell it which file to print, and so on. If you want to go that way, the cmd module is a great help.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement