how to access command line in a program

Hello guys,

My problem is simple, when I develop a program in command line I can perfrom anything what I want.

I have a class file and have a overloaded operator +.If I am in command line I can perform anything what I want but if i am in the program while it is executed  I have no choice except rawinput.I want my program let me write anything like in command line shell .

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

you might want to have a look a the "readline" library (unix availablity), this provides standard unix shell-like input (history, completion, etc).
hermescAuthor Commented:
NO I just need a command ( like rawinput) which lets me to pass variables expressions directly to program

for instance during my program instead rawinput my program will get this
and it will turn the value as if it is in shell
ok, I think I have you now...

eval( rawinput() )

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

for example:

print eval( raw_input( 'enter math equation: ' ) )
enter math equation: 10 + 20 * 100
ramromconsultant Commented:
Also consider the input() function, which equates to eval( rawinput() )

Bob Gailer, Page Editor
hermescAuthor Commented:
okey guys,
lets clear everything.I have got a class called polynomial.
For instance p=polynomial({1:1,2:2}) creates a polynomial X+X^2
now this can be entered in shell when you import the polynomial class.
Problem is my lecturer wants me to generate a "p" during the program.How can I do it? raw_input sucks.How can I get that polynomial while I am in program ( my class is ready and I am getting crazy !!! )
hermescAuthor Commented:
The original problem is on this site 
I have done the class.But dont know how to assign a polynomial ( p=polynomial(.....)) by using raw_input etc.....
hermescAuthor Commented:
lets increase it.....
hermescAuthor Commented:
hello guys,

I have found something
below code has imported poly class and in raw_input if you say

and execute it and print p it will work however
The user is not limited to p! So what can I do then?

while 1:
i=raw_input("Type something: ")
if i=="quit":
exec i
print "The value of p is:",p
hermescAuthor Commented:
Ok guys, I handle it

while 1:
      i=raw_input("type some")
      if i=="quit":
      exec i
if you type something executable such as polynomial.mult(a,b) and this polynomial member prints something then you display your expression !
ramromconsultant Commented:
Thanks for the link it gives some context.

I am often amazed at the extent of assignments in an "introductory class". This assignment is not trivial, especially for the 2nd assigment.

In order to meet the requirements for:

Enter a polynomial:
p = 7x^2 + 5

the program must
1 - get the variable name (p)
2 - get  the first term (7x^2) and split it into the c value (7) and the e value (2)
3 - execute p = Polynomial(e,c)
4 - get the next term (5) and split it into the c value (5) and the e value (0)
5 - execute p = p.add(Polynomial(e,c))

Am I on the right track for what you need?

Bob Gailer, Page Editor
'k, time to pay.  Grab it from here:
It does everything you want, and much more.  For example you can ask for p(p(x)').
hermescAuthor Commented:
Well guys,
thanks for your helps but I have done the code except I execute only p+q and not p+q+z' ( do not have idea how to find a solution for this).

Bob : yes ,

So far I have done except entering the polynomial like p=7x^14.... like that ( I still have to enter p=polynomial(....)
Seems like you don't like URLs.  I put an hour and wrote it from scratch.  You can pick the bits you like.  Here goes the complete code for the whole assignment:


class Polynomial:

      class Derivative:

      def __init__(p, e = None, c = None):
            if c == 0 or e == None:
                  p.__dict = {}
            elif e.__class__ == dict:
                  p.__dict = e.copy()
            elif e.__class__ == Polynomial:
                  p.__dict = e.__dict.copy()
                  p.__dict = {e: 1}
            if c <> None:
                  for key in p.__dict:
                        p[key] = p[key] * c
      def mult(p, q):
            r = Polynomial()
            if q.__class__ == Polynomial:
                  for a in p.__dict:
                        for b in q.__dict:
                              r[a+b] = r[a+b] + p[a] * q[b]
                  for key in p.__dict:
                        r[key] = p[key] * q
            return r

      def __mul__(p, q):
            return p.mult(q)

      def __rmul__(p, q):
            return p.mult(q)

      def __div__(p, q):
            # Only scalar division
            return p.mult(1/q)

      def __pow__(p, q):
            if q.__class__ == Polynomial.Derivative:
                  return p.derivative()
            elif q == 0:
                  r = Polynomial(0, 1)
            elif q == 1:
                  r = p.copy()
            elif q % 2 == 1:
                  r = p**int(q / 2)
                  r = r * r * p
            elif q % 2 == 0:
                  r = p**(q/2)
                  r = r * r
            return r

      def add(p, q):
            if q.__class__ == Polynomial:
                  r = p.copy()
                  for i in q.__dict:
                        r[i] += q[i]
                  r = p.add(Polynomial(0, q))
            return r

      def __add__(p, q):
            return p.add(q)

      def __radd__(p, q):
            return p.add(q)

      def __sub__(p, q):
            return p.add(-q)

      def __rsub__(p, q):
            return (-p).add(q)

      def negate(p):
            r = p.copy()
            for i in r.__dict:
                  r[i] = -r[i]
            return r

      def __neg__(p):
            return p.negate()

      def derivative(p):
            r = Polynomial()
            for i in p.__dict:
                  if i:
                        r[i-1] = p[i] * i
            return r
      def __invert__(p):
            return p.derivative()

      def getCoef(p, e):
            if p[e] == 0:
                  return (0, 0)
                  return (e, p[e])

      def __getitem__(p, i):
            return p.__dict.get(i, 0)

      def __setitem__(p, i, v):
            if v == 0:
                  if i in p.__dict:
                        del p.__dict[i]
                  p.__dict[i] = v
      def __str__(p):
            k = p.__dict.keys()
            if len(k):
                  s = ""
                  for i in k:
                        v = p[i]
                        if v < 0:
                              s += " - "
                              s += " + "
                        v = abs(v)
                        if v <> 1 or i == 0:
                              s += str(v)
                        if i <> 0:
                              s += "x"
                              if i <> 1:
                                    s += "^"+str(i)
                  if s[1] == "-":
                        s = s[1]+s[3:]
                        s = s[3:]
                  s = "(" + s + ")"
                  s = "0"
            return s
      def __call__(p, x):
            r = 0
            for i in p.__dict:
                  r += p[i] * x**i
            return r

      def copy(p):
            r = Polynomial()
              r.__dict = p.__dict.copy()
            return r

x = Polynomial(1)

if __name__ == "__main__":
      import re
      while True:
                  line = raw_input("Enter a polynomial: ")
            except EOFError:
            if line == "END":
            line = line.replace("^", "**")
            line = line.replace("'", "**Polynomial.Derivative()")
            (line, junk) = re.subn("([0-9])(x)", r"\1*\2", line)
            if not re.match(".*=", line):
                   line = "print " + line

                  exec line
            except Exception, e:
                  print e
mces, since this is homework, you should not provide complete solutions, only assist the author in areas of difficulty.

hermesc, I would take care if you decide to use mces' solution as your solution - there are several things that will loose you points from a homework perspective (complete lack of comments (sorry, there is one comment...), for one thing, other things also, including variable named something other than "self" for the object's self-reference in the class method definitions...) Also, since your assignment states that you may be chozen to present your assignment to the class, you would really want to know exactly how it works, etc...
hermesc, if there is a piece of code you are having problems with, post the code, and hopefully we can help you find the solution...
Hehe, I find the problem interesting enough to code the whole thing, but I didn't try to be too neat for exactly same reason.

BTW, the self thing, I found it really neat to use p instead of self in this special program.  Thanks for you comments.
hermescAuthor Commented:
Ok guys, I am almost in the end of the code

class polynomial:
      # type in increasing form of keys(orders)
      # p =polynomial({0:1,1:2,2:3,3:6})
      def __init__(self,x):
      def add(self,other):
            for j in range(len(other.coef)):
                  for i in range(len(self.coef)):
                        if tempe[i]==other.exp[j]:
                        else :
                  if c==0:
            for j in range(len(tempe)-1):
                  for i in range(len(tempe)-1):
                          if tempe[i]>tempe[j]:
                for i in range(len(tempc)-1):
                  print "%dx^%d+"%(tempc[i],tempe[i]),
            i =len(tempc)
            print "%dx^%d"%(tempc[i-1],tempe[i-1])


            for i in range(len(tempe)):

            return (res)
              def __add__(self,other):
            """overloading addition"""



This is a part of my code , when I type a+a+a+a ( polynomial it prints all the operations ( no problem with this and prints a the adress of a,  )

>>> a=polynomial({1:1,2:2,3:3})
>>> a+a+a+a
2x^1+ 4x^2+ 6x^3
3x^1+ 6x^2+ 9x^3
4x^1+ 8x^2+ 12x^3
<pazartesi.polynomial instance at 0x00A6D490>

hi Hermesc,

just a few comments,

1. Your post seems to have lost some formatting, which generally isn't a problem, but in Python it is, since Python uses indentation for block limitation....

2. in the add() method:


can be replaced with:
        tempe = self.coef[:]
        tempc = self.exp[:]

3. You definitely want to add some comments to the large loops in the add() method - this is a bit "magic", and is well worth explaining...

4. After the loops:

 i =len(tempc)
          print "%dx^%d"%(tempc[i-1],tempe[i-1])

can be replaced with:
          print '%dx%d' % ( tempc[-1], tempe[len(tempc)] )

or even
        print '%dx%d' % ( tempc[-1], tempe[-1] )
if len(tempc) == len( tempe )

It may be worth saying that the assignment described using lists of tupples to represent the polynomial, you are using 2 lists...
To convert a map (the {1:1...} construct) to a list to tupples use the following:

# sample mapping...
map = { 1:2, 2:3, 4:1 }
tupple_list = zip( map.keys(), map.values() )

Then accessing this:

coef_0 = tupple_list[ 0 ][COEF]

hope this helps...
hermescAuthor Commented:
guys thank you a lot! you earn more then  ( I have only 210 available ) 350. Thanks again a lot!
hermescAuthor Commented:
Meanwhile I will appreciate if you can provide me several computational exercises ( this is a introductional course but a 501 course, a masters :=) I am expected to develop graphical programs add the end of the course )
Thanks again
ramromconsultant Commented:
All please note the EE Member Agreement especially the last bullet under guidelines:
- Violating the guidelines for academic honesty or other unethical behavior,
  it is allowable to help a student with a project, but not doing it for them.

Bob Gailer, Page Editor
ramromconsultant Commented:
This is further clarified in the EE Help page

"Most commonly, this means that Experts are prohibited from doing your homework for you. They'll guide you and teach you, but don't ask them to write code to answer a question that seems like it was written for a test. It should be noted that just like bribery, while it's bad to offer a bribe, it's worse to take it -- so don't do homework.

"Homework" is loosely defined as an assigment, project or quiz offered up an instructor of a technical, trade or eductional institution as part of a scheduled course of instruction, for which the student receives some kind of credit. The Moderators know what homework looks like, and it will be your task to convince them it isn't."
Sorry.  Will not happen again.
Maybe I should have had written my ideas instead of implementing them.
Some notable ideas are:
  - Instead of parsing the string, MODIFY it and pass it to eval.
  - Since there is no postfix unary operator in python, I decided to use x**Some.Class() to represent x' (derivative).  Then in the __pow__, I can identify that all I'm asked to do is to call derivative.  This is the only easy way I can think of to make the derivative operator work.
  - Another idea is to define x as a Polynomial(0, 1).  It works automagically good with your overloaded operators.
  - __call__ can be overloaded for evaluating the polynomial, just using power, multiplication and addition, which means, you can then compute neat things like p(q(x)) with no additional burdon.

Thanks it,
Sorry again for breaking the rules.
Behdad Esfahbod
ramromconsultant Commented:
Thanks for appreciating and respecting the homework policy. And welcome to the team of Experts!

Bob Gailer, Page Editor
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.