Unity中C#如何执行cmd命令System.Diagnostics.Process的使用

在Unity中,我们可能需要自己写Editor工具。有时候我们可能还需要执行外部指令或者脚本(比如python脚本),这个时候,就需要用c#的System.Diagnostics.Process这个类了。

 

命名空间

using System.Diagnostics;

Process.Star()的构造方法

名称 说明
Process.Start () 启动(或重用)此 Process 组件的 StartInfo 属性指定的进程资源,并将其与该组件关联。
Process.Start (ProcessStartInfo) 启动由包含进程启动信息(例如,要启动的进程的文件名)的参数指定的进程资源,并将该资源与新的 Process 组件关联。
Process.Start (String) 通过指定文档或应用程序文件的名称来启动进程资源,并将资源与新的 Process 组件关联。
Process.Start (String,String) 通过指定应用程序的名称和一组命令行参数来启动一个进程资源,并将该资源与新的 Process 组件相关联。
Process.Start (String,String,SecureString,String) 通过指定应用程序的名称、用户名、密码和域来启动一个进程资源,并将该资源与新的 Process 组件关联起来。
Process.Start (String,String) 通过指定应用程序的名称和一组命令行参数、用户名、密码和域来启动一个进程资源,并将该资源与新的 Process 组件关联起来。

简单的接口封装

public static void RunCmd(string cmd,string args,string workdir=null)
{
    string[] res = new string[2];
    var p = CreateCmdProcess (cmd,args,workdir);
    res [0] = p.StandardOutput.ReadToEnd ();
    res [1] = p.StandardError.ReadToEnd ();
    p.Close ();
    return res;
}

public static System.Diagnostics.Process CreateCmdProcess(string cmd,string workdir=null)
{
    var pStartInfo = new System.Diagnostics.ProcessStartInfo (cmd);
    pStartInfo.Arguments = args;
    pStartInfo.CreateNoWindow = false;
    pStartInfo.UseShellExecute = false;
    pStartInfo.RedirectStandardError = true;
    pStartInfo.RedirectStandardInput = true;
    pStartInfo.RedirectStandardOutput = true;
    pStartInfo.StandardErrorEncoding = System.Text.UTF8Encoding.UTF8;
    pStartInfo.StandardOutputEncoding= System.Text.UTF8Encoding.UTF8;
    if(!string.IsNullOrEmpty(workdir))
        pStartInfo.WorkingDirectory = workdir;
    return System.Diagnostics.Process.Start(pStartInfo);
}

调用,假设我们想执行svn update的指令

var path = "D:\\Project\\";
RunCmd ("svn",string.Format("update \"{0}\"",path));

关于WorkingDirectory属性

WorkingDirectory属性指定可执行文件的位置。

如果WorkingDirectory是空字符串,则认为当前目录以包含可执行文件。

假设我们有一个py脚本test.py在D盘的py_pro目录中,即   D:\\py_pro\\test.py

我们要执行这个脚本,需要这样子

var workdir= "D:\\py_pro\\";
RunCmd ("python",workdir + "test.py",workdir);

更多例子 

// 打开记事本
System.Diagnostics.Process.Start("notepad.exe");        
// 打开计算器
System.Diagnostics.Process.Start("calc.exe ");                
// 打开注册表
System.Diagnostics.Process.Start("regedit.exe ");           
// 打开画图板
System.Diagnostics.Process.Start("mspaint.exe ");        
// 打开写字板
System.Diagnostics.Process.Start("write.exe ");              
// 打开播放器
System.Diagnostics.Process.Start("mplayer2.exe ");        
// 打开任务管理器
System.Diagnostics.Process.Start("taskmgr.exe ");          
// 打开事件查看器
System.Diagnostics.Process.Start("eventvwr.exe ");          
// 打开系统信息
System.Diagnostics.Process.Start("winmsd.exe ");           
// 打开Windows版本信息
System.Diagnostics.Process.Start("winver.exe ");              
// 发邮件
System.Diagnostics.Process.Start("mailto: "+ address);    

接口封装(详细版):

using System;
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Text;

class EdtUtil
{
    /// <summary>
    /// 构建Process对象,并执行
    /// </summary>
    /// <param name="cmd">命令</param>
    /// <param name="args">命令的参数</param>
    /// <param name="workingDri">工作目录</param>
    /// <returns>Process对象</returns>
    private static System.Diagnostics.Process CreateCmdProcess(string cmd,string workingDir = "")
    {
        var en = System.Text.UTF8Encoding.UTF8;
        if (Application.platform == RuntimePlatform.WindowsEditor)
            en = System.Text.Encoding.GetEncoding("gb2312");

        var pStartInfo = new System.Diagnostics.ProcessStartInfo(cmd);
        pStartInfo.Arguments = args;
        pStartInfo.CreateNoWindow = false;
        pStartInfo.UseShellExecute = false;
        pStartInfo.RedirectStandardError = true;
        pStartInfo.RedirectStandardInput = true;
        pStartInfo.RedirectStandardOutput = true;
        pStartInfo.StandardErrorEncoding = en;
        pStartInfo.StandardOutputEncoding = en;
        if (!string.IsNullOrEmpty(workingDir))
            pStartInfo.WorkingDirectory = workingDir;
        return System.Diagnostics.Process.Start(pStartInfo);
    }

    /// <summary>
    /// 运行命令,不返回stderr版本
    /// </summary>
    /// <param name="cmd">命令</param>
    /// <param name="args">命令的参数</param>
    /// <param name="workingDri">工作目录</param>
    /// <returns>命令的stdout输出</returns>
    public static string RunCmdNoErr(string cmd,string workingDri = "")
    {
        var p = CreateCmdProcess(cmd,workingDri);
        var res = p.StandardOutput.ReadToEnd();
        p.Close();
        return res;
    }

    /// <summary>
    /// 运行命令,不返回stderr版本
    /// </summary>
    /// <param name="cmd">命令</param>
    /// <param name="args">命令的参数</param>
    /// <param name="input">StandardInput</param>
    /// <param name="workingDri">工作目录</param>
    /// <returns>命令的stdout输出</returns>
    public static string RunCmdNoErr(string cmd,string[] input,workingDri);
        if (input != null && input.Length > 0)
        {
            for (int i = 0; i < input.Length; i++)
                p.StandardInput.WriteLine(input[i]);
        }
        var res = p.StandardOutput.ReadToEnd();
        p.Close();
        return res;
    }
	
    /// <summary>
    /// 运行命令
    /// </summary>
    /// <param name="cmd">命令</param>
    /// <param name="args">命令的参数</param>
    /// <returns>string[] res[0]命令的stdout输出,res[1]命令的stderr输出</returns>
    public static string[] RunCmd(string cmd,string workingDir = "")
    {
        string[] res = new string[2];
        var p = CreateCmdProcess(cmd,workingDir);
        res[0] = p.StandardOutput.ReadToEnd();
        res[1] = p.StandardError.ReadToEnd();
        #if !UNITY_IOS
        res[2] = p.ExitCode.ToString();
        #endif
        p.Close();
        return res;
    }
	
    /// <summary>
    /// 打开文件夹
    /// </summary>
    /// <param name="absPath">文件夹的绝对路径</param>
    public static void OpenFolderInExplorer(string absPath)
    {
        if (Application.platform == RuntimePlatform.WindowsEditor)
            RunCmdNoErr("explorer.exe",absPath);
        else if (Application.platform == RuntimePlatform.OSXEditor)
            RunCmdNoErr("open",absPath.Replace("\\","/"));
    }
}

使用

上面的RunCmd接口,return的string[],第0个是脚本的输出,第1个是错误输出

比如通过上面的RunCmd接口运行下面的python脚本

#python脚本: test.py,放在Assets/python目录中

print("Hello,I am python!")
print("This is a test")
try:
    print(1/0)
except BaseException,e:
    print("Error: " + str(e))
//c# 通过RunCmd接口执行python脚本

var workdir = Application.dataPath + "/python/";
var results = EdtUtil.RunCmd("python",workdir);
Debug.Log("python output: " + results[0]);
Debug.Log("python error: " + results[1]);

输出的结果是

python output: Hello,I am python!
This is a test
python error: Error: integer division or module by zero

我们可以在c#根据python返回的结果进行判断然后抛出c#的异常:

// c#抛出异常

if(results[0].LastIndexOf("Error") > 0)
{
    throw new System.Exception("python Error");
}

 

原文地址:https://linxinfa.blog.csdn.net

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


这篇文章将为大家详细讲解有关Unity3D中如何通过Animator动画状态机获取任意animation clip的准确播放持续时长,小编觉得挺实用的,因此分享给大家做个参考,
这篇文章主要介绍了Unity3D如何播放游戏视频,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解
这篇文章给大家分享的是有关Unity3D各平台路径是什么的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。1、Resources路径 Reso...
小编给大家分享一下Unity3D如何实现移动平台上的角色阴影,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!由于目前主流使用Unity3.x在移动平...
如何解析基于Unity3D的平坦四叉树地形与Virtual Texture的分析,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希
这篇文章主要介绍Unity3D如何实现动态分辨率降低渲染开销,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!之前项目降低分辨率我们都普...
这篇文章主要介绍了unity3d中如何使用屏幕空间改善shadowmap漏光,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编...
这篇文章主要介绍unity3d如何实现基于屏幕空间的描边,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!Outline(Based on Image Space)由...
这篇文章给大家分享的是有关unity3d中导入fbx时的Scale是什么的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。在Unity中点击GameOb...
这篇文章主要为大家展示了“unity3d中如何实现ttc转ttf及制作字体”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习
这篇文章主要介绍了unity3d中水彩风渲染有什么用,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了...
这篇文章将为大家详细讲解有关unity3d中图像压缩原理是什么,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。1 图像可压缩...
这篇文章给大家分享的是有关unity3d中光照公式有哪些的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。漫反射、高光、物理渲染(PBR...
小编给大家分享一下unity3d中光照探针的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我...
这篇文章将为大家详细讲解有关Unity3D中Rendering Paths及LightMode的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有
这篇文章将为大家详细讲解有关unity3d中图形学的光照原理是什么,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。首先,在...
这篇文章给大家分享的是有关unity3d中图片渲染流程是什么的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。相关名词GPU(Graphic Pr...
本篇我们来介绍一下左侧工具栏中基本绘制的应用。 一、墙体绘制直墙 & 矩形墙绘制墙体时,可以看到上方的工具栏中对墙体进行参数的设定。 弧形墙在建筑版的户...
xlua是由腾讯维护的一个开源项目,我们可以在github上下载这个开源项目并查看一些相关文档官网:https://github.com/Tencent/xLua配置文档:https://github.com/Tencent/xLua/blob/master/Assets/XLua/Doc/hotfix.md常见问题解答:https://github.com/Tencent/xLua/blob/master/Assets/
我们都知道,一个三维场景的画面的好坏,百分之四十取决于模型,百分之六十取决于贴图,可见贴图在画面中所占的重要性。在这里我将列举一些贴图,并且初步阐述其概念,理解原理的基础上制作贴图,也就顺手多了。我在这里主要列举几种UNITY3D中常用的贴图,与大家分享,希望对大家有帮助。01 首先