亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 C# 腳本運行 Python 應用程序并與之交互

從 C# 腳本運行 Python 應用程序并與之交互

元芳怎么了 2021-08-14 21:36:46
我正在嘗試使用 Unity C#(別擔心,很容易移植到普通 C#,但我目前沒有允許我這樣做的程序)使用以下代碼運行 python 應用程序,它基本上只是啟動一個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 應用程序是: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條經驗 獲得超6個贊

您需要配置您的進程,以便它知道將輸入從標準輸入流重定向到您的目標應用程序。在此處閱讀更多相關信息。


幾乎等于在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

    };


查看完整回答
反對 回復 2021-08-14
  • 1 回答
  • 0 關注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號