前言
有时候需要用代码执行一些命令行命令
C#代码
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System;
public class CommandTool
{
public static ExecuteCommandResult Excute(string fileName, string arguments)
{
List<string> msg = new List<string>();
Process p = new Process();
p.StartInfo.FileName = fileName;
p.StartInfo.Arguments = arguments;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.StandardOutputEncoding = Encoding.GetEncoding("gbk");
p.StartInfo.StandardErrorEncoding = Encoding.GetEncoding("gbk");
p.Start();
string resultStr = p.StandardOutput.ReadToEnd();
string errorStr = p.StandardError.ReadToEnd();
p.WaitForExit();
p.Close();
foreach (string str in resultStr.Split(new char[] { '\r' }))
{
msg.Add(str.Trim());
}
bool sucess = true;
if (errorStr != "")
{
sucess = false;
foreach (string str in errorStr.Split(new char[] { '\r' }))
{
msg.Add(str.Trim());
}
}
return new ExecuteCommandResult(sucess, msg);
}
public class ExecuteCommandResult
{
public bool sucess;
public List<string> msg;
public ExecuteCommandResult(bool sucess, List<string> msg)
{
this.sucess = sucess;
this.msg = msg;
}
override public string ToString()
{
string result = "";
msg.ForEach(v => result += v);
return result;
}
}
}
Python代码
无