Member Avatar for HTMLperson5

Is it possible to create a scripting language using Python?
Interactive Shell is fine, just something which comes close to a scripting language?
Which allows the user to script some sort of functionality?
Maybe more that just a console like this:

def main():
    cmd = (raw_input('#>>'))
    if cmd=="do_stuff":
        print "Ok, I will do stuff.."
        main()
    else:
        print cmd,
        print "is an unrecognised command."
        main()
print "*Shell*"
main()

So? Anything I could do?

Recommended Answers

All 24 Replies

You have infinite recursion.

What is wrong with Python itself? You could disallow the dangerous '_' character, though, for safety. Maybe only eval is OK. If you need control flow you must go with exec.

Is it possible to create a scripting language using Python?

Yes,but why?

Your script show that you have very much to learn before thinking about writing an other language in python.
An postet over now code is almost a joke with infinite recursion,do you know what this mean?
Programming language design concepts should be study for a long time before trying to make something useful.

Member Avatar for HTMLperson5

Programming language design concepts should be study for a long time before trying to make something useful.

Really? Something Useful? At least something which acts like a scripting language?
At least read a set of instructions from a file? In fact, the script I had shown previously could have been used in a "useful" way. Maybe with a few functionalities, ie. a text editor:

print "Specify Filename"
conf = (raw_input('>>'))
import os
os.system("cls") #Windows code :P
def content():

    d = open(conf, 'a')
    c = (raw_input(''))
    if c=="~finished~":
        d.close()
        quit()
    d.write(c)
    d.write("\n")
    content()
content()

It really depends on what you want to use it for.

Check out the "enaml" project from enthought. This is an example of a scripting language (or maybe a psuedo scripting language, I don't have a deep understanding really) that has been developed over python.

What is your motivation for pursuing this end? As the other posters have implied, you may find that basic Python's libaries are adequate to do what you need. Although, this doesn't mean you should not look into the idea; it sure would be a good learning experience if nothing else.

Member Avatar for HTMLperson5

basic Python's libaries are adequate

What modules do I use then?
I know i might want to use the code module, and builtins module.
But what else? Is this the correct approach?

There are a couple thing i want to clear up.
Just to make it very clear when you say a new scripting language.
This mean that you have to close python and not use python at all.

Then with the new language you can do something like this.

>>> print 'hello world'
hello world
>>> 2 + 2
4

This is not so easy as it look.

Which allows the user to script some sort of functionality?

Yes python can do a lot stuff,and this is no problem.
But i think bye you saying creating a new scripting language you create confusion
because creating a new language is a very diffcult task.
And i'm not sure that is your task.

It would help us considerably if you'd give us some idea of your goals, your design ideas, and your purpose in this. Is this solely as a learning experience, you do you have a particular application in mind for this new language?

Have you done any work on designing the language, and if so, could you give us some idea of the grammar and semantics you mean for it? (A simple BNF grammar for some basic statements, and some prose explanations of the intended behavior, should suffice). It would let us know what you have in mind, and may give us some idea of how to help you.

Member Avatar for HTMLperson5

Then with the new language you can do something like this.

Well, i can do abouts the same thing in even a limited language like javascript

<!doctype html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
        <title>HTMLperson5's scripting language :D</title>
    </head>
    <body>
        <div id="out"></div>
        <input id="in" tabindex="0"/>
    </body>
    <script type="text/javascript" src="http://yui.yahooapis.com/combo?3.5.0/build/yui/yui-min.js"></script>
    <script type="text/javascript">
        YUI().use("node", function(Y) {

            var COMMANDS = [
                {
                    name: "echo",
                    handler: doStuff
                },

                {
                    name: "greet",
                    handler: function(args) {
                        outputToConsole("Hello " + args[0] + ", welcome to HTMLperson5s creation.");
                    }
                }
            ];

            function processCommand() {
                var inField = Y.one("#in");
                var input = inField.get("value");
                var parts = input.replace(/\s+/g, " ").split(" ");
                var command = parts[0];
                var args = parts.length > 1 ? parts.slice(1, parts.length) : [];

                inField.set("value", "");

                for (var i = 0; i < COMMANDS.length; i++) {
                    if (command === COMMANDS[i].name) {
                        COMMANDS[i].handler(args);
                        return;
                    }
                }

                outputToConsole("Unsupported Command: " + command);
            }

            function doStuff(args) {
                outputToConsole("" + args);
            }

            function outputToConsole(text) {
                var p = Y.Node.create("<p>" + text + "</p>");
                Y.one("#out").append(p);
                p.scrollIntoView();
            }

            Y.on("domready", function(e) {
                Y.one("body").setStyle("paddingBottom", Y.one("#in").get("offsetHeight"));
                Y.one("#in").on("keydown", function(e) {
                    if (e.charCode === 13) {
                        processCommand();
                    }
                });
            });
        });
    </script>
</html>

there is the echo command. You use it like this:
echo <text_to_be_printed>
there is the greet command. You use it like this:
greet <name>

As you can see, I have made a sort of scripting language :P
I was thinking of doing something like this in Python.

Member Avatar for HTMLperson5

This mean that you have to close python and not use python at all.

What, so I use C# or something?

I don't think that this is quite what Snippsat meant (or at least I'll give him/her the benefit of the doubt). What Snippsat is saying is that if you are implementing something other than Python, you don't want to use Python's eval() or similar reflective techniques, as those are based on Python's syntax and semantics, not your languages; instead, you need to parse and interpret the new language as something unrelated to Python.

The language you write the interpreter in should not (in principle) affect how the interpreted language runs. Now, there are real-world considerations such as performance, availability of libraries, interfaces to th system and other languages, etc. that are impacted by the choice of implementation language, but for the most part, you can implement any language in any other (Turing-complete) language. If Python is what you want to use, go ahead and use Python; but don't rely on Python's ability to interpret itself as a way of implementing adifferent language.

What, so I use C# or something?

What is so hard to understand?,you can not use any language in all universe.
When you say creating a new script language it dos not excits.

Before python,C#,javascript was created they did not excits.
You can of course use theese languages to write stuff like a lexer,parser.
But when that is done your new language has to interpreter/compile all on it`s own.
If it use interpreter/compiler from other languages is not a new language.

As you can see, I have made a sort of scripting language :P

No no.
What you doing here is just to use feature of a languages to solve a specific task.
Also just what ordinary programming is all about.
It`s not a new script language because if you do not use javascript your program can not run.

Is this solely as a learning experience

What do you think.

I don't know quite what to think, actually. I am assuming that it is primarily to learn abot intrpreting languages; but if you have a specific goal in mind, it would help us if you said so, as we could give more specific advice.

Member Avatar for HTMLperson5

I don't know quite what to think, actually

Sir, doesn't it seem quite obvious?
If I have not explained why I was doing it, then it is for learning purposes!

Member Avatar for HTMLperson5

(Schol-R-LEA)

you don't want to use Python's eval() or similar reflective techniques,

(PyTony)

Maybe only eval is OK.

I'm confused.

OK, there does seem to be a bit of disagreement on this part, it is true. For my part, what I am arguing is that, even if you are using the same syntax and semantics as Python, if you are writing a significantly different language from Python you'd want to have your own expression evaluator rather than co-opt Python's. I think PyTony is thinking in terms of something a lot simpler than what I have in mind, however. Either that, or he's thinking of writing a partially meta-circular evaluator, which I hadn't thought to do myself.

I see the level of OP and with honest estimation it is not at level of language implementation, which is slightly above my own current coding practise, but more like RPG command level or simple <command> <arguments>.

You can accomplish quite a bit with Python and overloading operators, metaprogramming and stuff, if you are willing to make some compromizes, like changing what kind of operator symbols are used. If we move from Scheme to logic programming see for example: https://bitbucket.org/pcarbonn/pydatalog/wiki/Home and implementation in RPython of PyPy fame http://codespeak.net/pypy/extradoc/paper/prolog-in-python.pdf

Member Avatar for HTMLperson5

more like RPG command level or simple <command> <arguments>.

You have made something like this in reply to my question

Here is the code:

    from __future__ import print_function
    try:
        input, range = raw_input, xrange
    except NameError:
        pass

    def quit_():
        raise SystemExit

    def plus(a, b):
        return int(a)+int(b)

    commands = {'echo':print, 'quit':quit_, '+':plus}
    while True:
        c = input('>>').split(None, 1)
        if len(c) == 2:
            c, args = c
            args = args.split()
        elif c:
            c, args = c[0], []
        else:
            #empty line
            continue
    try:
        _ = commands[c](*args)
        if _:
            print(_)
    except KeyError:
        print('%s is not recognized command' % c)
    except TypeError:
        print('%s given wrong parameters: %s!' % (c, ' '.join(args)))
    except SystemExit:
        print('Bye, bye')
        break
    except ValueError:
        print('Problem with values of parameters for %s: %s' % (c, ' '.join(args)))

    """Output:
    >>ehco hi!
    ehco is not recognized command
    >>echo Hi, newbie!
    Hi, newbie!
    >>+ 12
    + given wrong parameters: 12!
    >>+ 1 2.3
    Problem with values of parameters for +: 1 2.3
    >>+ 1 1
    2
    >>quit
    Bye, bye
    >>>
    """

echo (command) text (argument)

Member Avatar for HTMLperson5

programs that automate the execution of tasks which could alternatively be executed one-by-one by a human operator.
--Wikipedia

This is all I really wanted to do! Any way?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.