C# 从C脚本运行Python应用程序并与之交互
我正在尝试使用Unity C别担心,很容易移植到普通的C,但我目前没有一个程序可以让我使用以下代码运行python应用程序,它基本上只是启动python程序并读取和写入一些输入和输出:C# 从C脚本运行Python应用程序并与之交互,c#,python,unity3d,C#,Python,Unity3d,我正在尝试使用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;
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 您需要配置流程,以便它知道如何将输入从标准输入流重定向到目标应用程序。请阅读更多关于此的信息 几乎相当于在您的应用程序中包含另一个属性初始化器:
我不知道C,但有可能p.StandardInput.WriteLine中的第一个换行符\n hi\n;被解释为python输入的行尾,因此它可能在等待另一个永远不会出现的输入。不用换行符就试试吧。是的,它消除了那个错误,但现在当我运行它时,它会被困在等待什么;我不知道发生了什么事。谢谢你的帮助!关于您的尝试,已经有了一些非常有用的问题:您正在用python脚本替换PYTHON3路径,对吗?不,我正在用python.exe应用程序的路径替换它。我看过那篇文章,但当我尝试输入python应用程序时,我的麻烦来了;该帖子只获取应用程序的输出。另外,如果您知道我与python文件通信的更好方法,请告诉我,我不完全确定问题出在哪里,但该过程有一系列事件可以订阅,您可以尝试使用它们来捕获输出,而不是StandardOutput.ReadToEnd。看看这家伙在做什么:至少你可以捕捉到在你写输入时可能发生的错误。祝你好运!
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
};