linux – Using cat command in Python for printing

linux – Using cat command in Python for printing

While theres no reason your code shouldnt work, this probably isnt 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, youll 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. Thats easy:

import shutil

while True:
    line = raw_input() # or just input() if youre 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—itll 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, e.g. shutil.copyfile) files methods (

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

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

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

linux – Using cat command in Python for printing

Leave a Reply

Your email address will not be published.