Zhonghui

每个不曾起舞的日子,都是对生命的辜负

User Tools

Site Tools


程序:csharp:运行外部程序

使用C#运行外部程序


C#应用

class Application
{
    static void Main()
    {
        var execPythonInfo = new System.Diagnostics.ProcessStartInfo();
 
        execPythonInfo.FileName = "python.exe"; // 程序
        execPythonInfo.Arguments = "--version"; // 参数
        execPythonInfo.UseShellExecute = false;
        execPythonInfo.RedirectStandardOutput = true;
 
        using (var runProcess = System.Diagnostics.Process.Start(execPythonInfo))
        {
            if (runProcess != null)
            {
                runProcess.WaitForExit();
 
                try
                {
                    Console.WriteLine(runProcess.ExitCode.ToString()); // 返回值
                }
                catch (System.Exception Ex)
                {
                    Console.WriteLine(Ex.Message);
                }
            }
        }
    }
}

在Unity中

运行其他程序,或者通过运行Python这样的解释器运行代码,都是可以的

#if UNITY_EDITOR
internal static class ParseWwiseJson
{
    private static readonly string s_converterScript = System.IO.Path.Combine(
        UnityEngine.Application.dataPath,
        "Script", "CSharp", "Wwise", "Tool", "ParseWwiseJson.py"
    );
 
    // Don't Run in Client
#if Art_Editor
    [UnityEditor.MenuItem("Wwise/Parse Wwise Json", false, (int)0)]
#endif
    public static void DoParseWwiseJson()
    {
        // Deprecation
        /*
        string pythonEnv = System.IO.File.ReadAllText(System.IO.Path.Combine(UnityEngine.Application.dataPath,
            "WwiseData", "Editor", "PyEnv.txt"
        ));
        */
 
        var start = new System.Diagnostics.ProcessStartInfo();
 
        // Deprecation
        // start.FileName = System.IO.Path.Combine(pythonEnv, "python.exe");
        start.FileName = "python.exe";
 
        start.Arguments = string.Format("\"{0}\" \"{1}\"", s_converterScript, UnityEngine.Application.dataPath);
        start.UseShellExecute = false;
        start.RedirectStandardOutput = true;
 
        using (var process = System.Diagnostics.Process.Start(start))
        {
            process.WaitForExit();
            try
            {
                if (process.ExitCode == 0) UnityEngine.Debug.Log("Wwise: Json to C# Define Updated");
                else UnityEngine.Debug.LogError("Wwise: Run Python Failed, " + process.ExitCode.ToString());
 
                UnityEditor.AssetDatabase.Refresh();
            }
            catch (System.Exception ex)
            {
                UnityEditor.AssetDatabase.Refresh();
 
                UnityEngine.Debug.LogError(string.Format("Wwise: Run C# Failed, {}", ex));
            }
        }
 
        // All Wwise Assets
        MarkWwiseAddressable.DoMarkWwiseAddressable();
    }
}
#endif // #if UNITY_EDITOR
/var/www/DokuWikiStick/dokuwiki/data/pages/程序/csharp/运行外部程序.txt · Last modified: 2023/05/05 07:13 by zh