Ad

C# Python Input Method Returns An Error

- 1 answer

I've just started to learn IronPython and I tried the code below which returned IronPython.Runtime.UnboundNameException: 'name 'hello' is not defined'.
Code:

var py = Python.CreateEngine();
var scope = py.CreateScope();
py.Execute(@"word = input('Input string\n')", scope);
var input = scope.GetVariable("word");
py.Execute("print " + input);

Console run ok, then it asked me to Input string, and I typed into "hello". And then it fired off the above error message. Then I tried this one just to see if it does without input method:

py.Execute(@"x = 2 + 3", scope);
py.Execute("print 'result'," + scope.GetVariable("x"));

So that one was ok.

Can someone please explain why can I not retrieve a variable from "input" method? and why is it an UnboundNameException?

Many thanks!

Ad

Answer

Having never worked with ironpython the answer lies within your own code.

your code:

py.Execute(@"word = input('Input string\n')", scope); (I type in dog)
var input = scope.GetVariable("word");
py.Execute("print " + input);

results in that last line saying py.Execute("print dog") ... but there is no dog varaible.

yet here:

py.Execute("print 'result'," + scope.GetVariable("x"));

You know to encapsulate text in quotes..

Id speculate that

py.Execute("print " + input);

Should read

py.Execute("print '" + input + "'");

Which results in print 'dog'

Ad
source: stackoverflow.com
Ad