Unity中-C#执行Cmd命令(System.Diagnostics.Process的使用)

这篇具有很好参考价值的文章主要介绍了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, String, SecureString, String)
通过指定应用程序的名称和一组命令行参数、用户名、密码和域来启动一个进程资源,并将该资源与新的 Process 组件关联起来。
using System;
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Text;
 
class EdtUtil
{
    ///
    /// 构建Process对象,并执行
    ///
    /// 命令
    /// 命令的参数
    /// 工作目录
    /// Process对象
    private static System.Diagnostics.Process CreateCmdProcess(string cmd, string args, 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);
    }
 
    ///
    /// 运行命令,不返回stderr版本
    ///
    /// 命令
    /// 命令的参数
    /// 工作目录
    /// 命令的stdout输出
    public static string RunCmdNoErr(string cmd, string args, string workingDri = "")
    {
        var p = CreateCmdProcess(cmd, args, workingDri);
        var res = p.StandardOutput.ReadToEnd();
        p.Close();
        return res;
    }
 
    ///
    /// 运行命令,不返回stderr版本
    ///
    /// 命令
    /// 命令的参数
    /// StandardInput
    /// 工作目录
    /// 命令的stdout输出
    public static string RunCmdNoErr(string cmd, string args, string[] input, string workingDri = "")
    {
        var p = CreateCmdProcess(cmd, args, 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;
    }
    ///
    /// 运行命令
    ///
    /// 命令
    /// 命令的参数
    /// string[] res[0]命令的stdout输出, res[1]命令的stderr输出
    public static string[] RunCmd(string cmd, string args, string workingDir = "")
    {
        string[] res = new string[2];
        var p = CreateCmdProcess(cmd, args, workingDir);
        res[0] = p.StandardOutput.ReadToEnd();
        res[1] = p.StandardError.ReadToEnd();
        p.Close();
        return res;
    }
    ///
    /// 打开文件夹
    ///
    /// 文件夹的绝对路径
    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 + "test.py", 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://www.toymoban.com/news/detail-761986.html

到了这里,关于Unity中-C#执行Cmd命令(System.Diagnostics.Process的使用)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Unity】使用 System.Windows.Forms 的问题

            因为最近开发需要用到使用 Windows 自带的窗口打开、文件选择等功能,然后兜兜转转需要使用  System.Windows.Forms 这个库。这个库在 WinForm 里是很常见的,但是要在 Unity 里使用,并打包出来还是有些坑的。         我这里使用的 Unity 版本:2022.2.1f1c1         PS:这个

    2023年04月08日
    浏览(26)
  • Android代码异常Calling a method in the system process without a qualified user

    问题原因: 有时候发现,startService或者sendBroadCast会产生此异常: 在没有合格用户的情况下调用系统进程中的方法。 经查,原因是由于系统应用尝试拉起普通应用抛出此异常,可能是在Android 4.2 之后Android引入多用户支持,有些特殊权限启动服务或者发送广播会失败。 如何修

    2024年02月12日
    浏览(31)
  • 提升Python os.system调用Shell的执行效率

      最近做了一个SDN流表的实验,在这个实验中,需要批量删除大量的流表项,使用了shell脚本。然而,我的流表数据存放在python字典中,我一开始是考虑每次读取一个字典并构造一条指令调用os.system(),然后发现这种方法效率非常糟糕。 我考虑问题可能出现在os.system()的调用上

    2023年04月21日
    浏览(25)
  • Unity中的异步编程【5】——在Unity中使用 C#原生的异步(Task,await,async) - System.Threading.Tasks

    1、System.Threading.Tasks中的Task是.Net原生的异步和多线程包。 2、UniTask(Cysharp.Threading.Tasks)是仿照.Net原生的Task,await,async开发的一个包,该包专门服务于Unity,所以取名UnityTask,简称UniTask。 3、既然有Task了,为啥还要搞一个UniTask (1)Task可以用在PC和Android上,但是在WebGL上则会

    2023年04月17日
    浏览(38)
  • 【Unity_Input System】Input System新输入系统(一)

    目录 一、导入Input System包 二、使用方式1:直接从输入设备对应类中获取输入 三、使用方式2:用代码创建InputAction获取输入 四、使用方式3:用Player Input组件获取输入 五、使用方式4:用Input Action Asset生成C#代码获取输入 打开包管理器,搜索Input System,点击右下角安装。 安装

    2024年02月08日
    浏览(31)
  • 【Unity_Input System】Input System新输入系统(二)

    目录 六、Action Phase 七、Input Action Asset文件 1.Bindings Mode  1Binding 2PositiveNegative Binding 3UpDownLeftRight Composite 4UpDownLeftRightForwardBackward Composite 5Binding with one modifier 6Binding with two modifier 2.Binding Path 3.Action Type 4.Initial State Check 5.Interaction 1Default Interaction 2Press Interaction 3Hold Inter

    2024年02月03日
    浏览(39)
  • 在window使用bat批处理文件执行cmd命令

    1、新建一个txt文本文档。然后在文档里面写入如下代码: 意思是在路径E:environmentELKlogstash-6.5.4bin执行logstash -f logstash.conf命令。路径、命令用隔开,命令之间也用隔开。如果还需要新增多条命令如Java-version则在logstash -f logstash.conf后面加java-version代码如下: 2、编辑好之后,

    2024年02月11日
    浏览(38)
  • 使用批处理文件(.bat)启动多个CMD窗口并执行命令

    由于每次启动本机的kafka都需要打开2个cmd窗口,分别启动zookeeper服务和kafka服务,操作相对繁琐,于是想起了批处理来帮忙一键启动。 在桌面新建一个txt文件,改后缀名为.bat,并加上下面的代码。 代码结尾不加pause的原因是,执行完关闭窗口,因为不需要该窗口保留着,免得

    2024年02月16日
    浏览(36)
  • docker system prune 命令详解

    该命令用于删除 Docker 系统中未使用的数据 官网描述 :删除所有未使用的容器、网络、映像(包括悬挂的和未引用的),以及卷(可选)。 名词解释: 未使用的容器 :所有已停止的容器将被删除。 未使用的镜像 :只有悬挂的镜像(未被任何容器引用)将被删除,除非使用

    2024年02月04日
    浏览(21)
  • Unity学习笔记:Job system

    Unity的job system可以让我们编写简单且安全的多线程代码,从而让我们的游戏可以使用所有可用的CPU内核来执行代码。这样可以提升我们的游戏的性能。 Unity的job system可以帮助我们写出多线程代码,从而我们的游戏可以使用所有可用的CPU内核来执行代码。job system为我们提供了

    2024年02月20日
    浏览(26)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包