简体   繁体   中英

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?

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.

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

So, you can just use basic (or anything else, eg 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)

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

under windows OS there is no cat command you should use type 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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM