【问题标题】:IronPython code not working in 3.4 but worked in 2.7IronPython 代码在 3.4 中不起作用,但在 2.7 中起作用
【发布时间】:2022-11-02 23:14:39
【问题描述】:

所以我安装了 IronPython 3.4 来替换我正在使用的 IronPython 2.7。下面的代码在 2.7 中运行良好,但是当我在 3.4 中使用它时出现错误: Microsoft.Scripting.SyntaxErrorException: 'invalid syntax' 有什么想法吗?谢谢。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromString("print 'Hello World!'");
            pythonScript.Execute();

        }
    }
}

尝试了上面的代码,它没有工作,但在 IronPython 2.7 中工作。

【问题讨论】:

  • print 是 python3 中的函数调用。
  • 它在 IronPython 2.7 中工作吗?

标签: python c# .net syntax ironpython


【解决方案1】:

IronPython 3.4 uses python 3.4 syntax 其中IronPython 2.7 使用python 2.7。

在 python 2.7 print 是一个语句,而在 python 3 print 是一个函数(这意味着你需要使用括号来包装参数)。因此,要使您的代码正常工作,您必须将以下部分从

pythonEngine.CreateScriptSourceFromString("print 'Hello World!'");
                                           ^^^^^^^^^^^^^^^^^^^^

pythonEngine.CreateScriptSourceFromString("print('Hello World!')");
                                           ^^^^^^^^^^^^^^^^^^^^^

【讨论】:

  • 好的谢谢。那么无论如何我可以让它运行,因为我是python的新手
  • @charliewhittaker 查看我的编辑。
  • 杰出的。太感谢了
猜你喜欢
  • 1970-01-01
  • 2016-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-05
  • 2015-09-03
  • 1970-01-01
  • 2016-06-04
相关资源
最近更新 更多