Search code examples
pythonlinuxpopen

Displaying images in linux terminal using Python


I am trying to use w3mimgdisplay to display images on the image terminal, and was looking at the source code for Ranger file manager. The file I was looking at can be found here.

Using this, I made a simple program.

import curses
from subprocess import Popen, PIPE

process = Popen("/usr/libexec/w3m/w3mimgdisplay",
                stdin=PIPE, stdout=PIPE, universal_newlines=True)

process.stdin.write("echo -e '0;1;100;100;400;320;;;;;picture.jpg\n4;\n3;'")
process.stdin.flush()
process.stdout.readline()
process.kill()

Whenever I enter

echo -e '0;1;100;100;400;320;;;;;picture.jpg\n4;\n3;' \ /usr/libexec/w3m/w3mimgdisplay

into the terminal, it prints the image properly, however, running the python script does nothing. How can I write the output of the program to the terminal?


Solution

  • the shell echo command adds newline to the end of its output (unless you use the -n switch which you didn't) so you need to mimic that by adding a newline at the end of your command too.

    Also, you should write the string contents, not the echo command itself, because this is being sent directly to the w3mimgdisplay process, not to the shell.

    I'm also unsure why readline. I suggest using the .communicate() command instead because it makes sure you don't get into a rare but possible read/write buffer race condition. Or, the best method, use the simpler subprocess.run() directly:

    import subprocess
    subprocess.run(["/usr/libexec/w3m/w3mimgdisplay"], 
        input=b'0;1;100;100;400;320;;;;;picture.jpg\n4;\n3;\n')