我正在嘗試使用 Unity C#(別擔(dān)心,很容易移植到普通 C#,但我目前沒有允許我這樣做的程序)使用以下代碼運行 python 應(yīng)用程序,它基本上只是啟動一個python程序并讀取和寫入一些輸入和輸出:using System.Collections;using System.Collections.Generic;using UnityEngine;using System;using System.Diagnostics;using System.IO; using System.Text;public class PythonSetup : MonoBehaviour { // Use this for initialization void Start () { SetupPython (); } void SetupPython() { string fileName = @"C:\sample_script.py"; Process p = new Process(); p.StartInfo = new ProcessStartInfo(pythonExe, "YOUR PYTHON3 PATH") { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; p.Start(); UnityEngine.Debug.Log (p.StandardOutput.ReadToEnd ()); p.StandardInput.WriteLine ("\n hi \n"); UnityEngine.Debug.Log(p.StandardOutput.ReadToEnd()); p.WaitForExit(); }}位于 C:/sample_script.py 的 python 應(yīng)用程序是:print("Input here:")i = input()print(i)C# 程序給了我錯誤:InvalidOperationException: Standard input has not been redirected System.Diagnostics.Process.get_StandardInput () (wrapper remoting-invoke-with-check) System.Diagnostics.Process:get_StandardInput ()提前感謝您的幫助!要放入普通的C#項目,只需將UnityEngine.Debug.Log替換為Console.WriteLine,將Start()替換為Main()。
1 回答

阿晨1998
TA貢獻2037條經(jīng)驗 獲得超6個贊
您需要配置您的進程,以便它知道將輸入從標(biāo)準(zhǔn)輸入流重定向到您的目標(biāo)應(yīng)用程序。在此處閱讀更多相關(guān)信息。
幾乎等于在ProcessStartInfo 中包含另一個屬性初始化器:
p.StartInfo = new ProcessStartInfo(pythonExe, "YOUR PYTHON3 PATH")
{
//You need to set this property to true if you intend to write to StandardInput.
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
添加回答
舉報
0/150
提交
取消