unity-工具-csharp与python交互


title: unity-工具-csharp与python交互
categories: Unity3d
tags: [unity, 编辑器, 扩展, python]
date: 2020-03-23 15:35:51
comments: false
mathjax: true
toc: true

很多时候写工具都是使用 python 来写, unity 工具需要调用 python 脚本并获取到执行结果.


使用到的就是 输出流 的获取.

  1. csharp 执行 命令行 的方法

    public static string ProcessCommand(string command, string argument) {
        ProcessStartInfo start = new ProcessStartInfo(command);
        start.Arguments = argument;
        start.CreateNoWindow = true;
        start.ErrorDialog = true;
        start.UseShellExecute = false; 
    
        start.RedirectStandardOutput = true;
        start.RedirectStandardError = true;
        start.RedirectStandardInput = true;
        start.StandardOutputEncoding = System.Text.UTF8Encoding.UTF8;
        start.StandardErrorEncoding = System.Text.UTF8Encoding.UTF8;
    
        Process p = Process.Start(start); 
    
        StringBuilder sb1 = new StringBuilder();
        StreamReader reader = p.StandardOutput;
        while (!reader.EndOfStream) {
            string line = reader.ReadLine();
            if (!line.StartsWith("---")) { // 过滤掉自定义的日志, 方便 py 调试
                sb1.Append(line);
            }
            if (!reader.EndOfStream) {
                sb1.Append("\n");
            }
        }
        reader.Close();
    
        StringBuilder sb2 = new StringBuilder();
        StreamReader errorReader = p.StandardError;
        while (!errorReader.EndOfStream) {
            sb2.Append(errorReader.ReadLine()).Append("\n");
        }
        errorReader.Close();
    
        p.WaitForExit();
        p.Close();
    
        if (sb2.Length > 0) {
            throw new Exception(string.Format("--- Error, python error, msg:{0}", sb2.ToString()));
        }
        return sb1.ToString();
    }
    
  2. python 工具脚本

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import sys
    
    if __name__ == "__main__":
        print("hello world, arg1: {}".format(sys.argv[1])) # 这个就能输出给 csharp
    
  3. 测试 csharp 执行 python 结果

    string pyPath = Path.Combine(PackConfig.PyToolDir, "tool.py");
    string res = EditorUtils.ProcessCommand("python3", string.Format("{0} {1}", pyPath, "getProjBranch"));
    Debug.LogFormat("--- py res: {0}", res);
    


你可能感兴趣的:(Unity3D)