#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Location
    Canada
    Posts
    51
    Rep Power
    2

    Basic text program


    I'm creating a basic budget program that consists a one class with different methods, and then a few other functions. My goal is to have it operate on command prompt but my issue is keeping it open and operating(simple input() at the end is not enough). I need it to be able to take input and respond similar to if I was using the interpreter. Importing the program works but I'd rather it be standalone. I've tried
    Code:
    while True:
        eval(input())
    This will work for the functions but not creating instances of the class and I'd rather not use eval(). I found cmd module thats seems like it will work. Does anyone know if this will work or if there is any others and which might better to use.

    thanks, Ryan

    PS: I can post code if it would help, I didn't think it would further explain it so I didn't
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2007
    Location
    Joensuu, Finland
    Posts
    431
    Rep Power
    67
    Originally Posted by Good News
    I need it to be able to take input and respond similar to if I was using the interpreter.
    Donít re-invent the wheel. Use the cmd module.
    My armada: openSUSE 13.1 (home desktop, home laptop), Crunchbang Linux 11 (mini laptop, work laptop), Android 4.2.1 (tablet)
  4. #3
  5. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,841
    Rep Power
    480
    See the main function.
    Code:
    import os
    import sys
    import time
    
    class Account:
    
        def __init__(self,log):
            self.Open = False
            self.balance = 0
            self.log = log
            with open(log) as transactions:
                for transaction in transactions:
                    self.transact(transaction)
            self.Open = True
    
        def __call__(self, transaction):
            transaction_clean = transaction.strip().lower()
            self.transact(transaction_clean)
            if self:
                fields = transaction_clean.split()
                s = ('#'[(fields[0] in set('deposit withdraw'.split())):] + 
                     transaction_clean + ' # ' + str(time.time()) + '\n')
                with open(self.log,'a') as transactions:
                    transactions.write(s)
    
        def __str__(self):
            return 'At {} the balance is {:.2f}'.format(time.ctime(),float(self))
    
        def __float__(self):
            return float(self.balance)
    
        def __bool__(self):
            return self.Open
    
        __nonzero__ = __bool__
    
        def transact(self, transaction):
            '''
                carry out the transaction.  If the transaction is invalid set the object to false
            '''
            fields = transaction.split()
            self.Open = not not (fields and (fields[0] in set('deposit withdraw balance'.split())))
            if self:
                action = fields[0]
                if action == 'balance':
                    print(self)
                else:
                    if action == 'rob': # Bad code, I cannot implement robbery as I'd like
                        amount = -self.balance
                    else:
                        try:
                            amount = float(fields[1])
                        except:
                            self.Open = False
                        else:
                            if action == 'withdraw':
                                amount *= -1
                    if self:
                        self.balance += amount
                        self.Open = 0 <= self.balance
    
    def main(filename):
        '''
            Invalid transcation terminates the program.
            Examples of valid transactions are:
                deposit 12.30
                withdraw 100
                balance
        '''
        print(main.__doc__)
        funds = Account('my.account')
        funds.transact('balance')
        while funds:
            sys.stdout.write('Transaction?  ')
            sys.stdout.flush()
            funds(sys.stdin.readline())
    
    if __name__ == '__main__':
        filename = 'my.account'
        print('warning: this program modifies the file {}.  Continue?'.format(filename))
        if 'y' == sys.stdin.readline()[:1].lower():
            try:
                os.stat(filename)
            except OSError:
                with open(filename,'w') as ouf:
                    pass
            main(filename) # sys.argv[1] could be the file name

    Comments on this post

    • Good News agrees : Way beyond what I ask!
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo