Clive Long
Clive Long

Reputation: 294

Python input file containing commands to be executed

I am working on an exercise where I am creating Python 3 functions that create and modify a stack, built upon Python lists. My function names include: createstack(), pop(), push() etc. Is it possible to create an input text file that contains a succession of commands that will execute the various functions? The structure of my code currently is:

def createstack():
.
.
def pop(stackin,data):
.
.
.
def push(stackin,data):
.
.
.
#main

I can test the functions by coding, for example, push(stack3,"dog") in the main section of the code. Can I achieve the same testing by putting the push, pop, createstack etc. in a file and somehow my routine can read the file then execute each line as if it was in the main part of my Python module?

I am developing and running the code using IDLE.

Upvotes: 0

Views: 109

Answers (2)

Jose A. García
Jose A. García

Reputation: 888

As they said the proper way of doing this is importing the module and run it as a regular python file, buy if you really want a plain text file, you can make some kind of toy language like:

push, "dog"
push, 3
push, False
pop
pop

And then do something to parse it:

from mystack import createstack, push, pop

class MyLangParser:
    COM_POP = "POP"
    COM_PUSH = "PUSH"

    def __init__(self):
        self.stack = createstack()

    def push(self, val):
        push(self.stack, val)

    def pop(self):
        return pop(self.stack)

    def parse(self, filename):
        with open(filename, "r") as f:
            data = f.readlines()
        for line in data:
            self.parse_line(line)
            print(self.stack)

    def parse_line(self, line):
        try:
            command, val = line.split(",")
            if command.strip().upper() == self.COM_PUSH:
                self.push(eval(val.strip())) # I don't like this, but it is the easiest (most dangerous) way.
            elif command.strip().upper() == self.COM_POP:
                self.pop()
            else:
                raise SyntaxError("Command not recognized")
        except ValueError:
            if line.strip().upper() == self.COM_POP:
                self.pop()
            else:
                raise SyntaxError("Command not recognized")

if __name__ == "__main__":
    parser = MyLangParser()
    parser.parse(sys.argv[1])

With the previous example, and the following functions

def createstack():
    return []

def push(alist, val):
    alist.append(val)

def pop(alist):
    return alist.pop()

the output is:

['dog']
['dog', 3]
['dog', 3, False]
['dog', 3]
['dog']

I hope that with this you recognize that the proper way of doing this is importing the module from other python file.

Upvotes: 0

Jonathan DEKHTIAR
Jonathan DEKHTIAR

Reputation: 3536

You should have a look to this tutorial, you should and can import your file from other python files:

https://en.wikibooks.org/wiki/A_Beginner%27s_Python_Tutorial/Importing_Modules

Upvotes: 4

Related Questions