gpt4 book ai didi

c# - C#Python输入法返回错误

转载 作者:行者123 更新时间:2023-12-02 10:51:15 25 4
gpt4 key购买 nike

我刚刚开始学习IronPython,并尝试了下面的代码,该代码返回了IronPython.Runtime.UnboundNameException: 'name 'hello' is not defined'
代码:

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);

控制台运行正常,然后要求我输入 Input string,然后输入 "hello"。然后,它触发了以上错误消息。然后,我尝试了这个,只是看看它是否没有 input方法:
py.Execute(@"x = 2 + 3", scope);
py.Execute("print 'result'," + scope.GetVariable("x"));

这样就可以了。

有人可以解释一下为什么我不能从 "input"方法中检索变量吗?为什么是 UnboundNameException

非常感谢!

最佳答案

从未与ironpython一起工作过,答案就在您自己的代码中。

您的代码:

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

导致最后一行显示py.Execute(“print dog”)...,但是没有狗变量。

还在这里:
py.Execute("print 'result'," + scope.GetVariable("x"));

您知道将文本封装在引号中。

我推测
py.Execute("print " + input);

应该读
py.Execute("print '" + input + "'");

这导致打印“狗”

关于c# - C#Python输入法返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49894685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com