Let us see how to create a Linux Terminal in Python. I will use a new framework, Kivy. Its a good GUI Framework, although not mature like Qt, GTK+ or wxWidgets. It is one of a very few multitouch toolkits available. Let us continue with it.
So, here is the source code. One is Python File and other is KV Lang File. Download them from here:
Creating a Linux Terminal in Python is very much easier than that in C. If you read my previous tutorial on “Simple Linux Terminal in C”, then you will notice that pty.fork() is similar to ptyFork() in previous tutorial. So, first thing is calling pty.fork(). It will return a tupple, containing 0 for child process (i.e. after fork()) and file descriptor for child process. Then use os.execv() to replace child process image with that of the bash. Now, use fcntl and termios to format your output.
After obtaining, the file descriptor you have to read and write to this file descriptor with os.write and os.read. Its pretty simple to write to doing a couple of string manipulations and getting the required data to be written. But the problem is with read. How you will read with your GUI not blocking. The answer lies in Clock.schedule_interval. Function readOutput will be called by the Kivy’s main loop every time to check whether data is available to read or not. To check this, select is used. Select and poll are two common APIs for I/O Multiplexing and in Python both has the wrapper available. Now, if data is available then read it using os.read and add to the Terminal.
I know it was pretty much simpler than the one in C. 😉