public void GeneratingPythonFunction()
        {
            Dictionary <string, object> context = new Dictionary <string, object>();

            context.Add("user", "alex");
            context.Add("age", 26);

            List <string> parameters = new List <string>(context.Keys);
            List <object> values     = new List <object>(context.Values);

            PythonEngine engine = new PythonEngine();

            engine.Execute(
                GenerateFunction("func", parameters.ToArray(), "return user + ' is ' + str(age) + ' years old'"));

            PythonFunction func1 = engine.EvaluateAs <PythonFunction>("func");

            engine.Execute(
                GenerateFunction("func", parameters.ToArray(),
                                 "return user + ' is ' + str(age+1) + ' years old next year'"));

            PythonFunction func2 = engine.EvaluateAs <PythonFunction>("func");

            object result1 = func1.Call(values.ToArray());

            Assert.AreEqual("alex is 26 years old", result1);

            object result2 = func2.Call(values.ToArray());

            Assert.AreEqual("alex is 27 years old next year", result2);
        }
        public void UntypedDelegateForPythonFunction()
        {
            Dictionary <string, object> context = new Dictionary <string, object>();

            context.Add("user", "alex");
            context.Add("age", 26);

            List <string> parameters = new List <string>(context.Keys);
            List <object> values     = new List <object>(context.Values);

            PythonEngine engine = new PythonEngine();

            engine.Execute(
                GenerateFunction("func", parameters.ToArray(), "return user + ' is ' + str(age) + ' years old'"));

            PythonFunction func1 = engine.EvaluateAs <PythonFunction>("func");

            UntypedDelegate func1Delegate = delegate(object[] param)

            {
                return(func1.Call(param));
            };

            object result1 = func1Delegate(values.ToArray());

            Assert.AreEqual("alex is 26 years old", result1);
        }
Пример #3
0
        private void RunPY(ThreadController controller, object state)
        {
            Engine.SetTrace(OnTracebackReceived);
            //ObjectOperations operations = Engine.CreateOperations(Scope);


            while (true)
            {
                try
                {
                    LastStartTime = DateTime.Now;

                    if (FirstRun)
                    {
                        FirstRun = false;
                    }

                    PythonFunction RunOneTimeAction = (PythonFunction)GetVariable("RunOneTime");
                    PythonCalls.Call(codeContext, RunOneTimeAction);

                    RunTimes++;
                    LastFinishTime = DateTime.Now;
                }catch (Exception ex)
                {
                }
            }
        }
Пример #4
0
        public bool RunOneTime()
        {
            RunThreadId = Thread.CurrentThread.ManagedThreadId;
            if (CompileSucess != true)
            {
                return(false);
            }

            try
            {
                Engine.SetTrace(OnTracebackReceived);

                LastStartTime = DateTime.Now;

                PythonFunction RunOneTimeAction = (PythonFunction)GetVariable("RunOneTime");
                PythonCalls.Call(codeContext, RunOneTimeAction);

                LastFinishTime = DateTime.Now;
                return(true);
            }catch (Exception ex)
            {
                YZXTaskExceptionEventArgs args = new YZXTaskExceptionEventArgs();
                args.exception = ex;
                ExceptionEvent(this, args);
            }
            return(false);
        }
Пример #5
0
        public static UnifiedInvokeResult InvokeFunc <T> (ISynchronizeInvoke synchronizer,
                                                          PythonFunction method)
        {
            Func <T> func = () => {
                return((T)PythonCalls.Call(method));
            };

            return(UnifiedSynchronizerAccess.Invoke(synchronizer, func, null));
        }
Пример #6
0
        public static void InvokeAction(ISynchronizeInvoke synchronizer,
                                        PythonFunction method)
        {
            Action action = () => {
                PythonCalls.Call(method);
            };

            UnifiedSynchronizerAccess.Invoke(synchronizer, action, null);
        }
Пример #7
0
 public object CallTarget(PythonFunction /*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14)
 {
     PythonOps.FunctionPushFrame(function.Context.LanguageContext);
     try {
         return(_target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14));
     } finally {
         PythonOps.FunctionPopFrame();
     }
 }
Пример #8
0
 public object CallTarget(PythonFunction /*!*/ function)
 {
     PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
     try {
         return(_target(function));
     } finally {
         PythonOps.FunctionPopFrame();
     }
 }
Пример #9
0
 public object CallTarget(PythonFunction /*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6)
 {
     PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
     try {
         return(_target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6));
     } finally {
         PythonOps.FunctionPopFrame();
     }
 }
Пример #10
0
 public object CallTarget(PythonFunction /*!*/ function, object arg0, object arg1, object arg2, object arg3)
 {
     try {
         PythonOps.FunctionPushFrame(function.Context.LanguageContext);
         return(_target(function, arg0, arg1, arg2, arg3));
     } finally {
         PythonOps.FunctionPopFrame();
     }
 }
Пример #11
0
 public void AddTask(PythonFunction func, int interval, int executeTimes, int waitTime, bool withArg = false)
 {
     if (withArg)
     {
         AddTask(task => PythonCalls.Call(func, task), interval, executeTimes, waitTime);
     }
     else
     {
         AddTask(task => PythonCalls.Call(func), interval, executeTimes, waitTime);
     }
 }
Пример #12
0
        StoreTyped(PythonFunction func)
        {
            uint   size = (uint)Marshal.SizeOf(typeof(PyFunctionObject));
            IntPtr ptr  = this.allocator.Alloc(size);

            CPyMarshal.Zero(ptr, size);
            CPyMarshal.WriteIntField(ptr, typeof(PyIntObject), "ob_refcnt", 1);
            CPyMarshal.WritePtrField(ptr, typeof(PyIntObject), "ob_type", this.PyFunction_Type);
            this.map.Associate(ptr, func);
            return(ptr);
        }
Пример #13
0
        public static void Schedule(PythonFunction func, double Time)
        {
            Timer timer = new Timer();

            timer.Interval = Time * 1000;
            timer.Elapsed += delegate(object sender, ElapsedEventArgs args){
                timer.Stop();
                ResourceManager.Engine.Operations.Invoke(func);
            };
            timer.Start();
        }
Пример #14
0
 private void AddTask(PythonFunction task, Func <int, int> interval, int executeTimes, int waitTime, bool withArg = false)
 {
     if (withArg)
     {
         AddTask(new ScheduledTask(t => PythonCalls.Call(task, t), interval, executeTimes, waitTime));
     }
     else
     {
         AddTask(new ScheduledTask(t => PythonCalls.Call(task), interval, executeTimes, waitTime));
     }
 }
Пример #15
0
        public static object signal(CodeContext /*!*/ context, int sig, object action)
        {
            //Negative scenarios - sig
            if (sig < 1 || sig >= NSIG)
            {
                throw PythonOps.ValueError("signal number out of range");
            }
            else if (Array.IndexOf(_PySupportedSignals, sig) == -1)
            {
                throw new RuntimeException("no IronPython support for given signal");
            }
            //Negative scenarios - action
            if (action == null)
            {
                throw PythonOps.TypeError("signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object");
            }
            else if (action.GetType() == typeof(int))
            {
                int tempAction = (int)action;
                if (tempAction != SIG_DFL && tempAction != SIG_IGN)
                {
                    throw PythonOps.TypeError("signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object");
                }
            }
            else if (action == default_int_handler)
            {
                //no-op
            }
            else
            {
                //Must match the signature of PySignalHandler
                PythonFunction result = action as PythonFunction;
                if (result == null)
                {
                    //It could still be something like a type that implements __call__
                    if (!PythonOps.IsCallable(context, action))
                    {
                        throw PythonOps.TypeError("signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object");
                    }
                }
            }

            object last_handler = null;

            lock (GetPythonSignalState(context).PySignalToPyHandler) {
                //CPython returns the previous handler for the signal
                last_handler = getsignal(context, sig);
                //Set the new action
                GetPythonSignalState(context).PySignalToPyHandler[sig] = action;
            }

            return(last_handler);
        }
Пример #16
0
        public override string GetNodeName(ITreeNavigator thisNode, object dataObject)
        {
            PythonFunction pyNode = dataObject as PythonFunction;

            List <string> args = new List <string> ();

            foreach (PythonArgument pyArg in pyNode.Arguments)
            {
                args.Add(pyArg.Name);
            }
            return(pyNode.Name + "(" + String.Join(", ", args.ToArray()) + ")");
        }
Пример #17
0
    public Func <object, Task <object> > CompileFunc(IDictionary <string, object> parameters)
    {
        string source = this.NormalizeSource((string)parameters["source"]);

        bool   sync = false;
        object tmp;

        if (parameters.TryGetValue("sync", out tmp))
        {
            sync = (bool)tmp;
        }

        // Compile to a Python lambda expression
        ScriptEngine   engine     = Python.CreateEngine();
        ScriptSource   script     = engine.CreateScriptSourceFromString(source, "path-to-py");
        PythonFunction pythonFunc = script.Execute() as PythonFunction;

        if (pythonFunc == null)
        {
            throw new InvalidOperationException("The Python code must evaluate to a Python lambda expression that takes one parameter, e.g. `lambda x: x + 1`.");
        }

        ObjectOperations operations = engine.CreateOperations();

        // create a Func<object,Task<object>> delegate around the method invocation using reflection

        if (sync)
        {
            return((input) =>
            {
                object ret = operations.Invoke(pythonFunc, new object[] { input });
                return Task.FromResult <object>(ret);
            });
        }
        else
        {
            return((input) =>
            {
                var task = new Task <object>(() =>
                {
                    object ret = operations.Invoke(pythonFunc, new object[] { input });
                    return ret;
                });

                task.Start();

                return task;
            });
        }
    }
Пример #18
0
        public static dynamic CallFunction(PythonFunction pythonFunction, List <object> arguments = null)
        {
            List <string> textArguments = null;

            if (arguments != null)
            {
                textArguments = EscapeArguments(arguments);
            }

            return(CallFunction(
                       pythonFunction.ToString(),
                       textArguments
                       ));
        }
Пример #19
0
        public override void Init()
        {
            try
            {
                scriptSource = Engine.CreateScriptSourceFromFile(Path);
                compiledCode = scriptSource.Compile();
                compiledCode.Execute(Scope);

                PythonFunction InitAction = (PythonFunction)GetVariable("Init");
                PythonCalls.Call(codeContext, InitAction);
            }
            catch (ImportException e)
            {
            }
        }
Пример #20
0
        public void Init()
        {
            try
            {
                Reload();

                InitThreadId = Thread.CurrentThread.ManagedThreadId;
                Engine.SetTrace(OnTracebackReceived);

                PythonFunction InitAction = (PythonFunction)GetVariable("Init");
                PythonCalls.Call(codeContext, InitAction);
            }
            catch (ImportException e)
            {
            }
        }
Пример #21
0
        public void Load(string file)
        {
            var          source = File.ReadAllText(file);
            ScriptEngine engine = Python.CreateEngine();

            engine.SetSearchPaths(new string[] {
                Path.Combine(_basePath, "ironpython", "lib")
            });
            ScriptSource script = engine.CreateScriptSourceFromString(source);

            _pythonFunc = script.Execute() as PythonFunction;
            if (_pythonFunc == null)
            {
                throw new InvalidOperationException("The Python code must evaluate to a Python lambda expression that takes one parameter, e.g. `lambda x: x + 1`.");
            }

            _operations = engine.CreateOperations();
        }
        public override bool Walk(FunctionDefinition node)
        {
            if (node.IsLambda)
            {
                return(base.Walk(node));
            }

            var function = new PythonFunction()
            {
                Name          = node.Name,
                Region        = GetDomRegion(node),
                Documentation = node.Documentation
            };

            var parameters = node.Parameters;

            for (int i = 0; i < parameters.Count; i++)
            {
                var param = parameters [i];

                string name = param.Name;
                if (param.IsList)
                {
                    name = "*" + name;
                }
                else if (param.IsDictionary)
                {
                    name = "**" + name;
                }

                var p = new PythonArgument()
                {
                    Name     = name,
                    Position = i
                };

                function.Arguments.Add(p);
            }

            containers.Peek().Functions.Add(function);
            containers.Push(function);

            return(base.Walk(node));
        }
Пример #23
0
        /// <summary>キャラを定められた仕様にもとづいてロードする。失敗すると例外が飛んでくる</summary>
        public static IHarrietCharacter LoadCharacter(string characterName)
        {
            var engine = Python.CreateEngine();
            //名前参照にexeのディレクトリとキャラのディレクトリを追加
            var paths = engine.GetSearchPaths();

            paths.Add(Environment.CurrentDirectory);
            paths.Add(DirectoryNames.GetCharacterScriptDirectory(characterName));
            paths.Add(DirectoryNames.GetCharacterLoadedDirectory(characterName));
            engine.SetSearchPaths(paths);

            string path = GetInitializeScriptPath(characterName);

            if (!File.Exists(path))
            {
                throw new FileNotFoundException($"file '{path}' was not found: this is needed to load character data");
            }
            engine.ExecuteFile(path, engine.Runtime.Globals);

            dynamic loadFunction;
            bool    result = engine.Runtime.Globals.TryGetVariable(CharacterLoadFunction, out loadFunction);

            if (!result)
            {
                throw new InvalidOperationException($"'{CharacterLoadFunction}' function does not exist in '{path}'");
            }
            PythonFunction function = loadFunction as PythonFunction;

            if (function == null)
            {
                throw new InvalidOperationException($"'{CharacterLoadFunction}' defined in '{path}' is not function");
            }

            IHarrietCharacter character = loadFunction() as IHarrietCharacter;

            if (character == null)
            {
                throw new InvalidOperationException($"{CharacterLoadFunction} result does not implements IHarrietCharacter");
            }

            return(character);
        }
        // We only try to add simple member expr, such "self.something",
        // which are most likely all the possibilites to declare/initialize
        // a class attribute (field).
        static bool IsSelfAttr(PythonFunction func, MemberExpression expr, out string attrName)
        {
            attrName = null;

            // NameExpression -> Simple name access
            var target = expr.Target as NameExpression;

            if (target == null)
            {
                return(false);
            }

            if (func.Arguments.Count == 0 ||
                func.Arguments [0].Name != target.Name)
            {
                return(false);
            }

            attrName = expr.Name;             // self.Name
            return(true);
        }
Пример #25
0
        private static void MapPythonFunction(IMethodSymbol target, string functionName, CsPyMapperDictionary typeDictionary)
        {
            var parameters = target.Parameters.Select(p => GetPythonParameter(p, typeDictionary)).ToList();

            PythonClass pythonClass;

            if (target.IsStatic)
            {
                pythonClass = parameters[0].Type.Node as PythonClass;
            }
            else
            {
                pythonClass = typeDictionary[target.ContainingType];
                parameters.Insert(0, new PythonParameter("self", new PythonType(pythonClass)));
            }

            var returnType = typeDictionary.GetPythonType(target.ReturnType);

            var pythonFunction = PythonFunction.Create(functionName, returnType, parameters);

            pythonClass.Children.Add(functionName, pythonFunction);
        }
Пример #26
0
 public MetaPythonFunction(Expression/*!*/ expression, BindingRestrictions/*!*/ restrictions, PythonFunction/*!*/ value)
     : base(expression, BindingRestrictions.Empty, value) {
     Assert.NotNull(value);
 }
Пример #27
0
 public static int Where(this PythonList list, PythonFunction function)
 {
     return(42);
 }
Пример #28
0
 public void AddTask(PythonFunction task, int interval, int executeTimes, int waitTime, bool withArg = false)
 {
     AddTask(task, i => interval, executeTimes, waitTime, withArg);
 }
Пример #29
0
 public void AddTask(PythonFunction task, PythonFunction interval, int executeTimes, int waitTime, bool withArg = false)
 {
     AddTask(task, i => (int)PythonCalls.Call(interval, i), executeTimes, waitTime, withArg);
 }
Пример #30
0
 public static object OriginalCallTarget10(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9)
 {
     function.__code__.LazyCompileFirstTarget(function);
     return(((Func <PythonFunction, object, object, object, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9));
 }
Пример #31
0
 public static object OriginalCallTarget4(PythonFunction function, object arg0, object arg1, object arg2, object arg3)
 {
     function.__code__.LazyCompileFirstTarget(function);
     return(((Func <PythonFunction, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3));
 }
        static ExceptionConverter()
        {
            exceptionInitMethod = new FunctionX(null, "__init__", new CallTargetN(ExceptionConverter.ExceptionInit), new string[] { "args" }, Ops.EMPTY, FunctionAttributes.ArgumentList);
            exceptionGetItemMethod = new FunctionX(null, "__getitem__", new CallTargetN(ExceptionConverter.ExceptionGetItem), new string[] { "args" }, Ops.EMPTY, FunctionAttributes.ArgumentList);
            exceptionStrMethod = new FunctionX(null, "__str__", new CallTargetN(ExceptionConverter.ExceptionToString), new string[] { "args" }, Ops.EMPTY, FunctionAttributes.ArgumentList);
            exceptionGetStateMethod= new FunctionX(null, "__getstate__", new CallTargetN(ExceptionConverter.ExceptionGetState), new string[] { "args" }, Ops.EMPTY, FunctionAttributes.ArgumentList);
            syntaxErrorStrMethod = new FunctionX(null, "__str__",
                new CallTargetN(ExceptionConverter.SyntaxErrorToString), new string[] { "args" }, Ops.EMPTY, FunctionAttributes.ArgumentList);
            unicodeErrorInit = new FunctionX(null,
                "__init__",
                new CallTargetN(ExceptionConverter.UnicodeErrorInit),
                new string[] { "self", "encoding", "object", "start", "end", "reason" }, Ops.EMPTY, FunctionAttributes.None);
            systemExitInitMethod = new FunctionX(null, "__init__", new CallTargetN(ExceptionConverter.SystemExitExceptionInit), new string[] { "args" }, Ops.EMPTY, FunctionAttributes.ArgumentList);

            for (int i = 0; i < exceptionMappings.Length; i++) {
                CreateExceptionMapping(null, exceptionMappings[i]);
            }

            defaultExceptionBaseType = nameToPython[new QualifiedExceptionName("Exception", defaultExceptionModule)];

            // we also have a couple of explicit bonus mappings.
            clrToPython[typeof(InvalidCastException)] = GetPythonException("TypeError");
            clrToPython[typeof(ArgumentNullException)] = GetPythonException("TypeError");
        }