从C#Scrip运行Python应用程序并与之交互

2024-09-19 15:57:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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();
    }
}

python应用程序,位于C:/sample_脚本.py,是:

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与控制台写入线将Start()替换为Main()。你知道吗


Tags: sampledebug程序log应用程序processsystemstart
1条回答
网友
1楼 · 发布于 2024-09-19 15:57:59

您需要配置流程,以便它知道如何将输入从标准输入流重定向到目标应用程序。阅读更多关于这个here。你知道吗

相当于在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
    };

相关问题 更多 >