Using the cat command in Python to print

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

cat file.txt > /dev/usb/lp0

From what I understand, this redirects the contents of file.txt to the print location. I tried using the following command

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

I thought this command would do the exact same thing, but it gave me the error "Allow denial." At the command prompt, I have to run the following command before concatenation.

sudo chown root:lpadmin /dev/usb/lp0

Is there a better way to do this?

+5
source share
2 answers

, , , , . , bash , python. , Python, , .

- shutil:

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

(, , , .)


, , , . :

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')

, - ​​ , , , , .. , cmd - .

+2

, UNIX - . .

, ( - , , shutil.copyfile) (http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files).

( ):

#  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)

. S. , system() ( ), .

0

All Articles