c# - 从 C# 脚本运行 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();
}
}
位于 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()。
解决方案
您需要配置您的流程,以便它知道将输入从标准输入流重定向到您的目标应用程序。在此处阅读有关此内容的更多信息。
几乎相当于在您的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
};
推荐阅读
- azure - Get-AzureRmSqlServerAuditing:术语“Get-AzSqlServerAuditing”未被识别为 cmdlet、函数、脚本文件的名称
- python - 训练时张量中的奇数形状和 ResourceExhaustedError:分配张量时出现 OOM
- python - Python在列表中搜索dict值:TypeError:'in
' 需要字符串作为左操作数,而不是列表 - css - Blazor:如何在运行时设置 CSS 类的背景图像?
- laravel - Sublime Goto 任何使用点符号的东西
- django - 我们如何为 Django models.dateTimeField 添加标签?
- python - 使用 Python pandas 数据框时返回副本与视图警告
- c# - 是否可以在 node.js 中编写 C# 样式的自定义属性?
- anaconda - 无法更新到 Anaconda Navigator 1.10.0 (Windows) - 卡在解决环境中
- python - Google Analytics Data API (GA4) Python 上的自定义维度