user2125538
user2125538

Reputation: 157

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?

Upvotes: 6

Views: 64462

Answers (3)

BARIS KURT
BARIS KURT

Reputation: 538

under windows OS there is no cat command you should usetype instead of cat under windows

(**if you want to run cat command under windows please look at: https://stackoverflow.com/a/71998867/2723298 )

import os
os.system('type a.txt > copy.txt')

..or if your OS is linux and cat command didn't work anyway here are other methods to copy file.. with grep:

   import os
    
   os.system('grep "" a.txt > b.txt')

*' ' are important!

copy file with sed:

os.system('sed "" a.txt > sed.txt')

copy file with awk:

os.system('awk "{print $0}" a.txt > awk.txt')

Upvotes: 0

Nick Baluk
Nick Baluk

Reputation: 2275

Remember, in UNIX - everything is a file. Even devices.

So, you can just use basic (or anything else, e.g. shutil.copyfile) files methods (http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files).

In your case code may (just a way) be like that:

#  Read file.txt
with open('file.txt', 'r') as content_file:
    content = content_file.read()
with open('/dev/usb/lp0', 'w') as target_device:
    target_device.write(content)

P. S. Please, don't use system() call (or similar) to solve your issue.

Upvotes: 0

abarnert
abarnert

Reputation: 365707

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.

Upvotes: 2

Related Questions