为了账号安全,请及时绑定邮箱和手机立即绑定

从 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 关注
  • 138 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号