简体   繁体   中英

Error While Running python code into C# , please how to solve it?

Hey everyone I'm trying to run script python into c# as I'm a beginner but I got this error Microsoft.Scripting.SyntaxErrorException: 'unexpected token 'from''

My C# code

using System;
using System.Windows.Forms;
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
using System.Collections.Generic;
using System.Linq;

namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void run_cmd(string cmd)
    {

        try
        {
            var engine = Python.CreateEngine();
            var paths = engine.GetSearchPaths();
            paths.Add(@"C:\Users\emady\AppData\Local\Programs\Python\Python310\Lib\site-packages");
            paths.Add(@"C:\Users\emady\AppData\Local\Programs\Python\Python310\Lib");
            engine.SetSearchPaths(paths);
            var scope = engine.CreateScope();
            scope.SetVariable(cmd,typeof(string));
            engine.ExecuteFile("C:\\Users\\emady\\Desktop\\test_file.py",scope);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "test");
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        run_cmd("ahmed");
    }
}

}

and my python code is

import cv2
def func(name):
f = open('C:\\Users\\emady\\PycharmProjects\\pythonProject\\venv\\' + name + '.txt', 
'w')
f.write('test')

But I don't know how to solve it The full Issue

and the error by details I don't know how to solve it please help

Microsoft.Scripting.SyntaxErrorException
HResult=0x80131500
  Message=unexpected token 'from'
  Source=IronPython
  StackTrace:
   at IronPython.Runtime.ThrowingErrorSink.Add(SourceUnit sourceUnit, String message, SourceSpan span, Int32 errorCode, Severity severity)
   at IronPython.Compiler.Parser.ReportSyntaxError(Int32 start, Int32 end, String message, Int32 errorCode)
   at IronPython.Compiler.Parser.ReportSyntaxError(Token t, IndexSpan span, Int32 errorCode, Boolean allowIncomplete)
   at IronPython.Compiler.Parser.ParsePrimary()
   at IronPython.Compiler.Parser.ParsePower()
   at IronPython.Compiler.Parser.ParseFactor()
   at IronPython.Compiler.Parser.ParseExpr(Int32 precedence)
   at IronPython.Compiler.Parser.ParseComparison()
   at IronPython.Compiler.Parser.ParseNotTest()
   at IronPython.Compiler.Parser.ParseAndTest()
   at IronPython.Compiler.Parser.ParseOrTest()
   at IronPython.Compiler.Parser.ParseExpression()
   at IronPython.Compiler.Parser.ParseExpressionList(Boolean& trailingComma)
   at IronPython.Compiler.Parser.ParseYieldExpression()
   at IronPython.Compiler.Parser.ParseYieldStmt()
   at IronPython.Compiler.Parser.ParseSmallStmt()
   at IronPython.Compiler.Parser.ParseSimpleStmt()
   at IronPython.Compiler.Parser.ParseStmt()
   at IronPython.Compiler.Parser.ParseSuite()
   at IronPython.Compiler.Parser.ParseIfStmtTest()
   at IronPython.Compiler.Parser.ParseIfStmt()
   at IronPython.Compiler.Parser.ParseStmt()
   at IronPython.Compiler.Parser.ParseSuite()
   at IronPython.Compiler.Parser.ParseLoopSuite()
   at IronPython.Compiler.Parser.ParseForStmt()
   at IronPython.Compiler.Parser.ParseStmt()
   at IronPython.Compiler.Parser.ParseSuite()
   at IronPython.Compiler.Parser.ParseIfStmtTest()
   at IronPython.Compiler.Parser.ParseIfStmt()
   at IronPython.Compiler.Parser.ParseStmt()
   at IronPython.Compiler.Parser.ParseSuite()
   at IronPython.Compiler.Parser.ParseClassOrFuncBody()
   at IronPython.Compiler.Parser.ParseFuncDef()
   at IronPython.Compiler.Parser.ParseStmt()
   at IronPython.Compiler.Parser.ParseFileWorker(Boolean makeModule, Boolean returnValue)
   at IronPython.Compiler.Parser.ParseFile(Boolean makeModule, Boolean returnValue)
   at IronPython.Runtime.PythonContext.ParseAndBindAst(CompilerContext context)
   at IronPython.Runtime.PythonContext.CompilePythonCode(SourceUnit sourceUnit, CompilerOptions options, ErrorSink errorSink)
   at IronPython.Runtime.PythonContext.GetScriptCode(SourceUnit sourceCode, String moduleName, ModuleOptions options, CompilationMode mode)
   at IronPython.Runtime.PythonContext.CompileModule(String fileName, String moduleName, SourceUnit sourceCode, ModuleOptions options, ScriptCode& scriptCode)
   at IronPython.Runtime.Importer.LoadModuleFromSource(CodeContext context, String name, String path)
   at IronPython.Runtime.Importer.LoadFromDisk(CodeContext context, String name, String fullName, String str)
   at IronPython.Runtime.Importer.ImportFromPathHook(CodeContext context, String name, String fullName, List path, Func`5 defaultLoader)
   at IronPython.Runtime.Importer.ImportFromPath(CodeContext context, String name, String fullName, List path)
   at IronPython.Runtime.Importer.ImportTopAbsolute(CodeContext context, String name)
   at IronPython.Runtime.Importer.ImportModule(CodeContext context, Object globals, String modName, Boolean bottom, Int32 level)
   at IronPython.Modules.Builtin.__import__(CodeContext context, String name, Object globals, Object locals, Object fromlist, Int32 level)
   at Microsoft.Scripting.Interpreter.FuncCallInstruction`7.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run7[T0,T1,T2,T3,T4,T5,T6,TRet](T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6)
   at IronPython.Runtime.Importer.ImportLightThrow(CodeContext context, String fullName, PythonTuple from, Int32 level)
   at IronPython.Runtime.Operations.PythonOps.ImportTop(CodeContext context, String fullName, Int32 level)
   at Microsoft.Scripting.Interpreter.FuncCallInstruction`4.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run1[T0,TRet](T0 arg0)
   at IronPython.Compiler.RuntimeScriptCode.InvokeTarget(Scope scope)
   at IronPython.Compiler.RuntimeScriptCode.Run(Scope scope)
   at IronPython.Runtime.PythonContext.InitializeModule(String fileName, ModuleContext moduleContext, ScriptCode scriptCode, ModuleOptions options)
   at IronPython.Runtime.PythonContext.CompileModule(String fileName, String moduleName, SourceUnit sourceCode, ModuleOptions options, ScriptCode& scriptCode)
   at IronPython.Runtime.Importer.LoadModuleFromSource(CodeContext context, String name, String path)
   at IronPython.Runtime.Importer.LoadPackageFromSource(CodeContext context, String name, String path)
   at IronPython.Runtime.Importer.LoadFromDisk(CodeContext context, String name, String fullName, String str)
   at IronPython.Runtime.Importer.ImportFromPathHook(CodeContext context, String name, String fullName, List path, Func`5 defaultLoader)
   at IronPython.Runtime.Importer.ImportFromPath(CodeContext context, String name, String fullName, List path)
   at IronPython.Runtime.Importer.ImportTopAbsolute(CodeContext context, String name)
   at IronPython.Runtime.Importer.ImportModule(CodeContext context, Object globals, String modName, Boolean bottom, Int32 level)
   at IronPython.Modules.Builtin.__import__(CodeContext context, String name, Object globals, Object locals, Object fromlist, Int32 level)
   at Microsoft.Scripting.Interpreter.FuncCallInstruction`7.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run7[T0,T1,T2,T3,T4,T5,T6,TRet](T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6)
   at System.Dynamic.UpdateDelegates.UpdateAndExecute6[T0,T1,T2,T3,T4,T5,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)
   at IronPython.Runtime.Importer.ImportLightThrow(CodeContext context, String fullName, PythonTuple from, Int32 level)
   at IronPython.Runtime.Operations.PythonOps.ImportTop(CodeContext context, String fullName, Int32 level)
   at Microsoft.Scripting.Interpreter.FuncCallInstruction`4.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 arg1)
   at IronPython.Compiler.PythonScriptCode.RunWorker(CodeContext ctx)
   at IronPython.Compiler.PythonScriptCode.Run(Scope scope)
   at IronPython.Compiler.RuntimeScriptCode.InvokeTarget(Scope scope)
   at IronPython.Compiler.RuntimeScriptCode.Run(Scope scope)
   at Microsoft.Scripting.SourceUnit.Execute(Scope scope, ErrorSink errorSink)
   at Microsoft.Scripting.Hosting.ScriptSource.Execute(ScriptScope scope)
   at Microsoft.Scripting.Hosting.ScriptEngine.ExecuteFile(String path, ScriptScope scope)
   at WindowsFormsApp1.Form1.run_cmd(String cmd) in C:\Users\emady\source\repos\WindowsFormsApp1\WindowsFormsApp1\Form1.cs:line 26
   at WindowsFormsApp1.Form1.Form1_Load(Object sender, EventArgs e) in C:\Users\emady\source\repos\WindowsFormsApp1\WindowsFormsApp1\Form1.cs:line 46
   at System.Windows.Forms.Form.OnLoad(EventArgs e)
   at System.Windows.Forms.Form.OnCreateControl()
   at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   at System.Windows.Forms.Control.CreateControl()
   at System.Windows.Forms.Control.WmShowWindow(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
   at System.Windows.Forms.Form.WmShowWindow(Message& m)
   at System.Windows.Forms.Form.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

  This exception was originally thrown at this call stack:
    [External Code]
    WindowsFormsApp1.Form1.run_cmd(string) in Form1.cs
    WindowsFormsApp1.Form1.Form1_Load(object, System.EventArgs) in Form1.cs
    [External Code]

I solved it by clearing import cv2 this line and I edited my c# code as that

    var var1 = "samy";
    ScriptEngine engine = Python.CreateEngine();
    ScriptScope scope = engine.CreateScope();
    engine.ExecuteFile("C:\\Users\\emady\\Desktop\\test_file.py", 
    scope);
    dynamic testFunction = scope.GetVariable("func");
    var result = testFunction(var1);

but why my line didn't write('test')??

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM