Search code examples
pythoncygwinxterm

Python send a command to Xterm


I have a python script that opens up file for me in emacs, and to do that it calls a process in xterm like so

"""AutoEmacs Document"""

# imports
import sys
import os
import psutil
import subprocess
from argparse import ArgumentParser

# constants
xlaunch_config = "C:\\cygwin64\\home\\nalis\\Documents\\experiments\\emacs\\Autoemacs\\config.xlaunch"
script = "xterm -display :0 -e emacs-w32 --visit {0}"
# exception classes

# interface functions

# classes


# internal functions & classes

def xlaunch_check():
    # checks if an instance of Xlaunch is running
    xlaunch_state = []
    for p in psutil.process_iter(): #list all running process
        try:
            if p.name() == 'xlaunch.exe':# once xlaunch is found make an object
                xlaunch_state.append(p)
        except psutil.Error: # if xlaunch is not found return false
            return False
    return xlaunch_state != [] #double checks that xlaunch is running

def xlaunch_run(run):
    if run == False:
        os.startfile(xlaunch_config)
        return 0 #Launched
    else:
        return 1 #Already Running


def emacs_run(f):
    subprocess.Popen(script.format(f))
    return 0#Launched Sucessfully

def sysarg():
    f = sys.argv[1]
    il = f.split()
    l = il[0].split('\\')
    return l[(len(l) - 1)]

def main():
    f = sysarg()
    xlaunch_running = xlaunch_check()
    xlaunch_run(xlaunch_running)
    emacs_run(f)
    return 0


if __name__ == '__main__':
    status = main()
    sys.exit(status)
`

and it works fairly fine with the occasional bug, but I want to make it a little more versatile by having python send the Xterm console it launches commands after it launched like "-e emacs-w32" and such based off of the input it receives. I've already tried something like this:

    # A test to send Xterm commands
import subprocess
xterm = subprocess.Popen('xterm -display :0', shell=True)
xterm.communicate('-e emacs')

but that doesn't seem to do anything. besides launch the terminal. I've done some research on the matter but it has only left me confused. Some help would be very much appreciated.


Solution

  • To open emacs in terminal emulator, use this:

    Linux;

    Popen(['xterm', '-e', 'emacs']) 
    

    Windows:

    Popen(['cmd', '/K', 'emacs'])
    

    For cygwin use:

    Popen(['mintty', '--hold', 'error', '--exec', 'emacs'])