简体   繁体   English

通过C#脚本运行Python应用程序并与之交互

[英]Run And Interact With Python Application from C# Script

I'm trying to use Unity C# (don't worry, easy to port to normal C# but I don't currently have a program that lets me do so) to run a python application using the following code, which basically just starts a python program and reads and writes some input and output: 我正在尝试使用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();
    }
}

The python application, located at C:/sample_script.py, is: 位于C:/sample_script.py的python应用程序是:

print("Input here:")
i = input()
print(i)

The C# program gives me the error: C#程序给我错误:

InvalidOperationException: Standard input has not been redirected System.Diagnostics.Process.get_StandardInput () (wrapper remoting-invoke-with-check) System.Diagnostics.Process:get_StandardInput ()

Thanks for the help ahead of time! 感谢您的提前帮助!

To put into normal C# project, just replace UnityEngine.Debug.Log with Console.WriteLine and replace Start() with Main(). 要放入普通的C#项目中,只需将UnityEngine.Debug.Log替换为Console.WriteLine,然后将Start()替换为Main()。

You need to configure your process so it knows to redirect input from the Standard Input stream and to your target application. 您需要配置流程,使其知道将输入从标准输入流重定向到目标应用程序。 Read more about this here . 在此处阅读有关此内容的更多信息。

Pretty much just amounts to including another property initialiser in your ProcessStartInfo : 几乎等于在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
    };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM