Search code examples
c#ironpython

IronPython in a C# application - SyntaxErrorException: 'invalid syntax'


I am trying to execute some python using IronPython in a C# WPF application. The code below works without the 'import os' line is removed. With that line I get a SyntaxErrorException: 'invalid syntax' error. I believe that is the correct syntax?

    public MainWindow()
    {
        InitializeComponent();

        ScriptEngine pythonEngine = Python.CreateEngine();
        var paths = pythonEngine.GetSearchPaths();
        paths.Add(@"C:\Python38\Lib");
        pythonEngine.SetSearchPaths(paths);

        ScriptScope scope = pythonEngine.CreateScope();
        scope.SetVariable("App", this);

        ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromString(@"
import os
f = open('demofile4.txt', 'a') 
f.write('Now the file has more content!')
f.close()");
        pythonScript.Execute(scope);
    }

Solution

  • I have this working now. IronPython isn't compatible with Python 3.8. From the website:

    IronPython 3.4 uses Python 3.4 syntax and standard libraries

    I downloaded Python 3.4.10 and, in my code, changed:

    paths.Add(@"C:\Python38\Lib");
    

    To:

    paths.Add(@"C:\Python-3.4.10\Lib");