Python terminal application management

I have a server program that runs through the console. (In particular, the Bukkit MineCraft server) I would like to be able to control this program and read the result. There is no GUI, so it should not be too complicated, right?

In any case, I never controlled the console in python and was completely stuck. Any suggestions?

PS I am using Debian Linux, so this should simplify things a bit.

I got a pretty good answer, but I also need one more thing. I want to have some way to print the FULL program output to the python console (line by line in order), and I need the console commands to be redirected to the program.

+4
source share
2 answers

The canonical answer for such a task is to use Pexpect .

Pexpect is a Python module for spawning child applications and automatically managing them. Pexpect can be used to automate interactive applications such as ssh, ftp, passwd, telnet, etc. It can be used to automate installation scripts to duplicate software package installations on different servers. It can be used for automatic software testing. Pexpect is in the spirit of Waiting for Don Libes, but Pexpect is pure Python. Other Expect-like modules for Python require TCL and Expect, or require compilation of C extensions. Pexpect does not use C, Expect, or TCL extensions. It should work on any platform that supports the standard Python pty module. The Pexpect interface is designed for ease of use, making it easy to complete simple tasks.

+5
source

You can try creating an interactive shell inside Python, something like:

import sys import os import subprocess from subprocess import Popen, PIPE import threading class LocalShell(object): def __init__(self): pass def run(self): env = os.environ.copy() p = Popen('open -a Terminal -n', stdin=PIPE, stdout=PIPE, stderr=subprocess.STDOUT, shell=True, env=env) sys.stdout.write("Started Local Terminal...\r\n\r\n") def writeall(p): while True: # print("read data: ") data = p.stdout.read(1).decode("utf-8") if not data: break sys.stdout.write(data) sys.stdout.flush() writer = threading.Thread(target=writeall, args=(p,)) writer.start() try: while True: d = sys.stdin.read(1) if not d: break self._write(p, d.encode()) except EOFError: pass def _write(self, process, message): process.stdin.write(message) process.stdin.flush() 
0
source

All Articles