Python Shell 1
This is the most basic python shell I've done. In fact it is not even a shell. For example you cannot change the current directory, and that makes it quite unusable in real world (provided that you would use a toy example in real world anyway).
As you can see it does the same things that the c simple shell.
Still you can see much better the logic of the application, without worrying with memory management and string operations. While in the C example you need a separate funcion, the Python standard library does provide the appropriate funcion.
#!/usr/bin/python
# -*- Coding: utf-8 -*-
import os
import sys
while True:
cmd = raw_input('$ ').strip()
if cmd == "exit": sys.exit(0)
if cmd == "": continue
pid = os.fork()
if pid ==0:
argv = cmd.split()
try:
os.execvp(argv[0], argv)
except OSError:
print >>sys.stderr,\
"command not found: %s" \
% argv[0]
sys.exit(0)
else:
print "Wait for child (%d)" % pid
res = os.wait()
print "(%d) child quit with %d" % res
os.fork()
It creates a new process, identical to current process. In the parent process it returns the child PID, in the child returns 0.os.execvp(...)
execvp uses $PATH to search the executable pointed by the first argument. The second is the list of parameters it will be called with. The new executable replaces the current one (so it does not return to this code). If it doen not find the executable, it raises OSError.os.wait()
Waits for a generic child process. We do not need to check which one. Being syncronous, we have just one child. In this example we start working with asyncronous stuff.Please note that we could have used just os.spawn* and not worry about forking and all. You can see it here or in an absurd example with threading here
back