예제 #1
0
        void TestInstance()
        {
            PythonInstance py = new PythonInstance(@"
import UnityEngine
from UnityEngine import *

class PyClass:
    index = 1

    def __init__(self):
        pass

    def somemethod(self):
        self.index += 1
        Camera.main.transform.position = Vector3(2,2,-5);
        Debug.Log(""in some method"" + str(self.index))

    def isodd(self, n):
        return 1 == n % 2
");

            py.CallMethod("somemethod");
            py.CallMethod("somemethod");
            py.CallMethod("somemethod");
            py.CallMethod("somemethod");
            Debug.Log(py.CallFunction("isodd", 6));
        }
        private IMember GetValueFromMember(MemberExpression expr)
        {
            if (expr?.Target == null || string.IsNullOrEmpty(expr.Name))
            {
                return(null);
            }

            IPythonInstance instance = null;
            var             m        = GetValueFromExpression(expr.Target);

            if (m is IPythonType typeInfo)
            {
                var member = typeInfo.GetMember(expr.Name);
                // If container is class/type info rather than the instance, then the method is an unbound function.
                // Example: C.f where f is a method of C. Compare to C().f where f is bound to the instance of C.
                if (member is PythonFunctionType f && !f.IsStatic && !f.IsClassMethod)
                {
                    return(f.ToUnbound());
                }
                instance = new PythonInstance(typeInfo);
            }

            instance = instance ?? m as IPythonInstance;
            var type  = m?.GetPythonType(); // Try inner type
            var value = type?.GetMember(expr.Name);

            if (type is IPythonModule)
            {
                return(value);
            }

            // Class type GetMember returns a type. However, class members are
            // mostly instances (consider self.x = 1, x is an instance of int).
            // However, it is indeed possible to have them as types, like in
            //  class X ...
            //  class C: ...
            //      self.x = X
            // which is somewhat rare as compared to self.x = X() but does happen.

            switch (value)
            {
            case IPythonClassType _:
                return(value);

            case IPythonPropertyType prop:
                return(prop.Call(instance, prop.Name, ArgumentSet.Empty));

            case IPythonType p:
                return(new PythonBoundType(p, instance, GetLoc(expr)));

            case null:
                Log?.Log(TraceEventType.Verbose, $"Unknown member {expr.ToCodeString(Ast).Trim()}");
                return(UnknownType);

            default:
                return(value);
            }
        }
예제 #3
0
        public IMember GetValueFromCallable(CallExpression expr)
        {
            if (expr?.Target == null)
            {
                return(null);
            }

            var target = GetValueFromExpression(expr.Target);

            target?.AddReference(GetLocationOfName(expr.Target));

            var result = GetValueFromGeneric(target, expr);

            if (result != null)
            {
                return(result);
            }

            // Should only be two types of returns here. First, an bound type
            // so we can invoke Call over the instance. Second, an type info
            // so we can create an instance of the type (as in C() where C is class).
            IMember value = null;

            switch (target)
            {
            case IPythonBoundType bt:     // Bound property, method or an iterator.
                value = GetValueFromBound(bt, expr);
                break;

            case IPythonInstance pi:
                value = GetValueFromInstanceCall(pi, expr);
                break;

            case IPythonFunctionType ft:     // Standalone function or a class method call.
                var instance = ft.DeclaringType != null ? new PythonInstance(ft.DeclaringType) : null;
                value = GetValueFromFunctionType(ft, instance, expr);
                break;

            case IPythonClassType cls:
                value = GetValueFromClassCtor(cls, expr);
                break;

            case IPythonType t:
                // Target is type (info), the call creates instance.
                // For example, 'x = C; y = x()' or 'x = C()' where C is class
                value = new PythonInstance(t);
                break;
            }

            if (value == null)
            {
                Log?.Log(TraceEventType.Verbose, $"Unknown callable: {expr.Target.ToCodeString(Ast).Trim()}");
            }

            return(value);
        }
예제 #4
0
        public async Task <IMember> GetValueFromCallableAsync(CallExpression expr, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (expr?.Target == null)
            {
                return(null);
            }

            var target = await GetValueFromExpressionAsync(expr.Target, cancellationToken);

            // Should only be two types of returns here. First, an bound type
            // so we can invoke Call over the instance. Second, an type info
            // so we can create an instance of the type (as in C() where C is class).
            IMember value = null;

            switch (target)
            {
            case IPythonBoundType bt:     // Bound property, method or an iterator.
                value = await GetValueFromBoundAsync(bt, expr, cancellationToken);

                break;

            case IPythonInstance pi:
                value = await GetValueFromInstanceCall(pi, expr, cancellationToken);

                break;

            case IPythonFunctionType ft:     // Standalone function or a class method call.
                var instance = ft.DeclaringType != null ? new PythonInstance(ft.DeclaringType) : null;
                value = await GetValueFromFunctionTypeAsync(ft, instance, expr, cancellationToken);

                break;

            case IPythonClassType cls:
                value = await GetValueFromClassCtorAsync(cls, expr, cancellationToken);

                break;

            case IPythonType t:
                // Target is type (info), the call creates instance.
                // For example, 'x = C; y = x()' or 'x = C()' where C is class
                value = new PythonInstance(t, GetLoc(expr));
                break;
            }

            if (value == null)
            {
                Log?.Log(TraceEventType.Verbose, $"Unknown callable: {expr.Target.ToCodeString(Ast).Trim()}");
            }

            return(value);
        }
    public static void main(string[] args)
    {
        PythonInstance py = new PythonInstance(@"
class PyClass:
    def __init__(self):
        pass

    def somemethod(self):
        print 'in some method'

    def isodd(self, n):
        return 1 == n % 2
");

        py.CallMethod("somemethod");
        Console.WriteLine(py.CallFunction("isodd", 6));
    }
예제 #6
0
        public override bool canPerform(Event proposedEvent, Universe environment)
        {
            if (!base.canPerform(proposedEvent, environment)) //checks all the dependent subsystems
            {
                return(false);
            }

            dynamic perform = PythonInstance.canPerform(proposedEvent, environment);

            //This needs to be inside the python canPerform
            //IsEvaluated = true;
            //if ((bool)perform == false)
            //    return false;
            //var newProf = Convert.ChangeType(CollectorType, DependencyCollector());
            //newState.addValue(KEY, );
            return((bool)perform);
        }
예제 #7
0
        public ScriptedSubsystem(string filePath, string className, Dependencies dependencies, Type collectorType)
        {
            Name          = className;
            CollectorType = collectorType;
            var engine = Python.CreateEngine();
            var scope  = engine.CreateScope();
            var ops    = engine.Operations;

            engine.ExecuteFile(filePath, scope);
            var pythonType = scope.GetVariable(className);

            PythonInstance = ops.CreateInstance(pythonType);
            Dictionary <string, Delegate> newDependencies = PythonInstance.getDependencyDictionary();

            dependencies.Append(newDependencies);
            SubsystemDependencyFunctions = PythonInstance.getDependencyDictionary();
        }
예제 #8
0
        private async Task <IMember> GetValueFromMemberAsync(MemberExpression expr, CancellationToken cancellationToken = default)
        {
            if (expr?.Target == null || string.IsNullOrEmpty(expr.Name))
            {
                return(null);
            }

            IPythonInstance instance = null;
            var             m        = await GetValueFromExpressionAsync(expr.Target, cancellationToken);

            if (m is IPythonType typeInfo)
            {
                var member = typeInfo.GetMember(expr.Name);
                // If container is class/type info rather than the instance, then the method is an unbound function.
                // Example: C.f where f is a method of C. Compare to C().f where f is bound to the instance of C.
                if (member is PythonFunctionType f && !f.IsStatic && !f.IsClassMethod)
                {
                    return(f.ToUnbound());
                }
                instance = new PythonInstance(typeInfo);
            }

            instance = instance ?? m as IPythonInstance;
            var type  = m.GetPythonType(); // Try inner type
            var value = type?.GetMember(expr.Name);

            switch (value)
            {
            case IPythonClassType _:
                return(value);

            case IPythonPropertyType prop:
                return(prop.Call(instance, prop.Name, ArgumentSet.Empty));

            case IPythonType p:
                return(new PythonBoundType(p, instance, GetLoc(expr)));

            case null:
                Log?.Log(TraceEventType.Verbose, $"Unknown member {expr.ToCodeString(Ast).Trim()}");
                return(UnknownType);

            default:
                return(value);
            }
        }
예제 #9
0
        public ScriptedSubsystem(XmlNode scriptedSubXmlNode, Dependencies dependencies)
        {
            Name = scriptedSubXmlNode.Attributes["Name"].Value.ToString();
            string pythonFilePath = scriptedSubXmlNode.Attributes["src"].Value.ToString();

            CollectorType = Type.GetType(scriptedSubXmlNode.Attributes["CollectorType"].Value.ToString());
            var engine = Python.CreateEngine();
            var scope  = engine.CreateScope();
            var ops    = engine.Operations;

            engine.ExecuteFile(pythonFilePath, scope);
            var pythonType = scope.GetVariable(Name);

            PythonInstance = ops.CreateInstance(pythonType);
            Dictionary <string, Delegate> newDependencies = PythonInstance.getDependencyDictionary();

            dependencies.Append(newDependencies);
            SubsystemDependencyFunctions = PythonInstance.getDependencyDictionary();
        }
예제 #10
0
        public IMember GetValueFromIndex(IndexExpression expr)
        {
            if (expr?.Target == null)
            {
                return(null);
            }

            var target = GetValueFromExpression(expr.Target);
            // Try generics first since this may be an expression like Dict[int, str]
            var result = GetValueFromGeneric(target, expr);

            if (result != null)
            {
                return(result);
            }

            if (expr.Index is SliceExpression || expr.Index is TupleExpression)
            {
                // When slicing, assume result is the same type
                return(target);
            }

            var type = target.GetPythonType();

            if (type != null)
            {
                if (!(target is IPythonInstance instance))
                {
                    instance = new PythonInstance(type);
                }
                var index = GetValueFromExpression(expr.Index);
                if (index != null)
                {
                    return(type.Index(instance, new ArgumentSet(new [] { index }, expr, this)));
                }
            }

            return(UnknownType);
        }
        public async Task <IMember> GetValueFromIndexAsync(IndexExpression expr, CancellationToken cancellationToken = default)
        {
            if (expr?.Target == null)
            {
                return(null);
            }

            var target = await GetValueFromExpressionAsync(expr.Target, cancellationToken);

            // If target is a generic type, create specific class
            if (target is IGenericType gen)
            {
                return(await CreateSpecificFromGenericAsync(gen, expr, cancellationToken));
            }

            if (expr.Index is SliceExpression || expr.Index is TupleExpression)
            {
                // When slicing, assume result is the same type
                return(target);
            }

            var type = target.GetPythonType();

            if (type != null)
            {
                if (!(target is IPythonInstance instance))
                {
                    instance = new PythonInstance(type);
                }
                var index = await GetValueFromExpressionAsync(expr.Index, cancellationToken);

                return(type.Index(instance, index));
            }

            return(UnknownType);
        }
예제 #12
0
        //public void WriteLog(string info, int type = 3)
        //{
        //    UserInfo userInfo = LoginUserInfo.Get();
        //    LogEntity logEntity = new LogEntity();
        //    logEntity.F_CategoryId = type;
        //    logEntity.F_OperateTypeId = "0";// ((int)OperationType.Visit).ToString();
        //    logEntity.F_OperateType = "其它";
        //    logEntity.F_OperateAccount = userInfo.account;
        //    logEntity.F_OperateUserId = userInfo.userId;
        //    logEntity.F_Module = "(PYTHON)" + "/Scripts/" + CurrentModuleName + "";
        //    logEntity.F_ExecuteResult = type == 4 ? 0 : 1;
        //    logEntity.F_ExecuteResultJson = info;
        //    logEntity.WriteLog();
        //}
        #endregion 属性桥接
        private ActionResult PY(RouteData Route)
        {
            /*
             * 以双下划线开始并以双下划线结束的控制器名 如要访问person.py 则 /__person__/{action}的方式
             */
            string moduleName      = Route.Values["controller"].ToString();
            string action_name     = Route.Values["action"].ToString();
            string controller_name = "";
            //if (Route["Controller"].ToString() == "Dynamic" && dynamicRoute.Contains("scripts/"))
            //{

            //    string[] tmp = dynamicRoute.Split('/');
            //    if (tmp.Length > 2)
            //    {
            //        moduleName = controller_name = tmp[1];
            //        action_name = tmp[2];
            //    }

            //}
            var            s  = this.Request.HttpContext;//.RequestContext;
            PythonInstance py = null;

            //moduleName =  moduleName.Replace("__", "");
            //controller_name = controller_name.Replace("__", "");
            string controler_file = contentRootPath + "/Scripts/Controllers/" + moduleName + "/" + moduleName + ".py";

            IList <string> libPath = new List <string>();

            libPath.Add(contentRootPath + "/Scripts/Controllers");
            dynamic ret = null;

            if (System.IO.File.Exists(controler_file))
            {
                controller_name = moduleName;
                try
                {
                    py = new PythonInstance(controler_file, libPath);
                }
                catch (Exception e)
                {
                    //this.WriteLog(e.Message, 4);
                    return(Content(e.Message));
                }


                var p = Route.Values["id"] != null ? Route.Values["id"].ToString() : null;

                try
                {
                    py.run(controller_name);
                    py.CallMethod("initMVC", this);
                }
                catch (Exception e)
                {
                    //this.WriteLog(e.Message, 4);
                    return(Content(e.Message));
                }

                try
                {
                    CurrentModuleName = controller_name + "/" + action_name;
                    if (p == null)
                    {
                        ret = py.CallFunction(action_name);
                    }
                    else
                    {
                        ret = py.CallFunction(action_name, p);// py.execute_action(controller_name + "." + action_name);
                    }
                }
                catch (Exception e)
                {
                    //this.WriteLog(e.Message, 4);
                    return(Content("模块:" + CurrentModuleName + "(" + e.Message + ")"));
                }

                if (ret == null)
                {
                    return(Content(""));
                }
                if (ret.GetType() == typeof(JsonResult) || ret.GetType() == typeof(ActionResult) || ret.GetType() == typeof(ViewResult) || ret.GetType() == typeof(ContentResult))
                {
                    return(ret);
                }
            }
            else
            {
                //throw new System.Exception("功能未实现");
                ret = "脚本未找到";

                Response.StatusCode = 404;
                //this.WriteLog(ret + ":" + controler_file, 4);
            }
            var x = new ContentResult();

            x.Content = ret;//{new {Content=dynamicRoute}};// View(dynamicRoute);// View(viewFile);
            return(x);
        }
예제 #13
0
        public override bool canExtend(Event proposedEvent, Universe environment, double evalToTime)
        {
            dynamic extend = PythonInstance.canExtend(proposedEvent, environment, evalToTime);

            return((bool)extend);
        }
 public PythonCalculatorController(PythonInstance python)
 {
     _python = python;
 }