Achim Domma (Procoders) wrote:
I'm writing a simple shell using cmd.Cmd. It would be very usefull if I
could read the commands as batchjob from a file. I've tried the following:
class MyShell(cmd.Cmd ):
def __init__(self,s tdin):
cmd.Cmd.__init_ _(self,stdin=st din)
...
...
if __name__=='__ma in__':
if len(sys.argv)== 2:
shell=MyShell(f ile(sys.argv[1]))
else:
shell=MyShell(s ys.stdin)
shell.cmdloop()
Calling 'myshell.py inputfile' with an invalid inputfile, I get an
error, so it seems that the file is opened. But the shell starts as
usuall, ignoring the content of the file. There is no output and no
errors (if I write nonsens into the inputfile).
[While I'm at it, duplicated from de.comp.lang.py thon]
Interesting idea. The simplest approach I found was to feed the file
directly into the cmdqueue-Attribute:
import cmd
class Cmd(cmd.Cmd):
****def*do_this (self,*arg):
********print*" this>",*arg
****def*do_that (self,*arg):
********print*" *****<that",*ar g
****def*do_quit (self,*arg):
********print*" That's*all,*fol ks"
********return* True
if __name__ == "__main__":
****import*optp arse
****parser*=*op tparse.OptionPa rser()
****parser.add_ option("-i",*"--interactive",*a ction="store_tr ue")
****options,*ar gs*=*parser.par se_args()
****
****c*=*Cmd()
****try:
********filenam e,*=*args
****except*Valu eError:
********pass
****else:
********c.cmdqu eue.extend(file (filename))
********if*not* options.interac tive:
************c.c mdqueue.append( "quit\n")
****
****c*=*c.cmdlo op()
$ cat batch.txt
this
that
that
oops
that
$ python2.4 batch_cmd.py batch.txt
this>
*****<that
*****<that
*** Unknown syntax: oops
*****<that
That's all, folks
If you want to continue the session in the interaktive mode:
$ python2.4 batch_cmd.py batch.txt -i
this>
*****<that
*****<that
*** Unknown syntax: oops
*****<that
(Cmd)
Peter