473,915 Members | 5,000 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

read input for cmd.Cmd from file

Hi,

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).

Could anybody help?

regards,
Achim
Jul 19 '05 #1
2 2400
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

Jul 19 '05 #2
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:


[...]

Your original approach should work too if you clear the use_rawinput flag
and provide a do_EOF() method that handles the file end:

import cmd

class Cmd(cmd.Cmd):
def do_this(self, arg):
print "this>", arg
def do_that(self, arg):
print " <that", arg
def do_quit(self, arg):
print "That's all, folks"
return True
do_EOF = do_quit

if __name__ == "__main__":
import sys
filename = sys.argv[1]
c = Cmd(stdin=file( filename))
c.use_rawinput = False
c = c.cmdloop()

Peter

Jul 19 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
9021
by: Gunnar | last post by:
Hello, I've just written a CPP program that reads integers from a binary file, and used this code while (my_ifstram.read( (char* ) &number, sizeof(int)) { // do something with number } My question is now, where can I find a manual that describes what the read method does with the ifstream object? I'm sitting here with my Linux/Debian machine, but I have not found any
18
4906
by: jas | last post by:
Hi, I would like to start a new process and be able to read/write from/to it. I have tried things like... import subprocess as sp p = sp.Popen("cmd.exe", stdout=sp.PIPE) p.stdin.write("hostname\n") however, it doesn't seem to work. I think the cmd.exe is catching it.
3
2758
by: Bill Cohagan | last post by:
I'm writing a console app in c# and am encountering a strange problem. I'm trying to use redirection of the standard input stream to read input from a (xml) file. The following code snippet is from this app: =============================== static void Main(string args) { if (args.Length > 0) Console.SetIn(new StreamReader(args)); //executes if I don't use the "<", ">" redirection syntax when invoking XmlTextReader xmlin = new...
10
2555
by: Tibby | last post by:
I need to read/write not only text files, but binary as well. It seems like on binary files, it doesn't right the last 10% of the file. -- Thanks --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.538 / Virus Database: 333 - Release Date: 11/10/2003
8
23918
by: a | last post by:
I have a struct to write to a file struct _structA{ long x; int y; float z; } struct _structA A; //file open write(fd,A,sizeof(_structA)); //file close
1
4012
by: Jose Reckoner | last post by:
I'm running python 2.3 on Windows XP. Anyone have a quick small script to convert .DT1 and .DEM data to ASCII or some other format? I don't need a viewer. Thanks!
8
1892
by: kepioo | last post by:
I currently have an xml input file containing lots of data. My objectiv is to write a script that reports in another xml file only the data I am interested in. Doing this is really easy using SAX. The input file is continuously updated. However, the other xml file should be updated only on request. Everytime we run the script, we track the new elements in the input file and report them in the output file.
6
2496
by: portCo | last post by:
Hello there, I am creating a vb application which is some like like a questionare. Application read a text file which contains many questions and display one question and the input is needed from user to calculate the score. Here is a problem. I can read a text file. However, it's read whole file at a time. So,
9
3858
by: vineeth | last post by:
Hello all, I have come across a weird problem, I need to determine the amount of bytes read from a file, but couldn't figure it out , My program does this : __ file = open("somefile") data = file.read() print "bytes read ", len(data) ---
63
3293
by: Bill Cunningham | last post by:
I don't think I can do this without some help or hints. Here is the code I have. #include <stdio.h> #include <stdlib.h> double input(double input) { int count=0,div=0; double mean=0,linput=0; FILE *fpr, *fpw;
0
10039
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9881
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10923
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10542
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9732
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8100
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7256
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4778
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4344
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.