Search code examples
bashpython-2.7vte

Best Way of redirecting output to a VTE terminal


Which is the best way of redirect the output of a command to a VTE terminal?

i came with this idea:

On the VTE execute:

tty > /usr/tmp/terminal_number    

then read the file from the python program:

with open('/usr/tmp/terminal_number', 'r') as f:
    self.VTE_redirect_path=f.readline()

then execute the bash commands, for exemple:

os.system('''echo "foo" >  {0}'''.format(self.VTE_redirect_path))

The problem of this method is that the file terminal_number containing /dev/pts/# needs to be refreshed. Also i don't really like the idea of having to create files to communicate. Is there any direct solution?


Solution

  • In VTE you use terminal.feed("string")

    See vte_terminal_feed.

    With python Popen is the suggested method to execute commands. If you are wanting to use commands then you should do this.

    #Uncomment the next line to get the print() function of python 3
    #from __future__ import print_function
    import os
    import subprocess
    from subprocess import Popen
    command = "echo \"something\""
    env = os.environ.copy()
    try:
        po = Popen(command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE,
            universal_newlines=True, env=env)
        po.wait()
        output, error_output = po.communicate()
    
        if po.returncode:
            print(error_output)
        else:
            print(output)
    
    except OSError as e:
        print('Execution failed:', e, file=sys.stderr)
    

    If you want to use gtk with gtk vte then do this instead.

    #place the following in a method of a vte instance
    env = os.environ.copy()
    try:
        po = Popen(command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE,
            universal_newlines=True, env=env)
        po.wait()
        output, error_output = po.communicate()
    
        if po.returncode:
            print(error_output)
        else:
            self.feed(output) #here you're printing to your terminal.
    
    except OSError as e:
        print('Execution failed:', e, file=sys.stderr)
    

    For the finest control in a regular terminal you can try the cmd module. This will require that you produce your own prompt so it is a more specific option to get what you want.