【问题标题】:Not able to get multiple strings output from python script using c#无法使用 c# 从 python 脚本中获取多个字符串输出
【发布时间】:2019-01-25 05:41:32
【问题描述】:

我有一个富文本框,我在其中插入字符串值:- Archit Panda。

但我只从 python 脚本获取输出为“Archit”。

按钮上的 C# 代码:-

private void button13_Click(object sender, RoutedEventArgs e) {

        TextRange textRange = new TextRange(richTextBox1.Document.ContentStart,richTextBox1.Document.ContentEnd);
        string str = textRange.Text;
        string FileName = @"C:\Users\Archit\AppData\Local\Programs\Python\Python37-32\python.exe";
       // string myPythonApp = @"""C:\Users\Archit\Documents\Visual studio 2010\Projects\WpfApplication1\WpfApplication1\blockchain.py""";
        string myPythonApp = @"blockchain.py";
        ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(FileName);

        myProcessStartInfo.UseShellExecute = false;
        myProcessStartInfo.RedirectStandardOutput = true;
        //Console.WriteLine(splitted.ToString());
        myProcessStartInfo.Arguments = myPythonApp+ " " +str;
        Process myProcess = new Process();
        myProcess.StartInfo = myProcessStartInfo;
        myProcess.Start(); 
        StreamReader myStreamReader = myProcess.StandardOutput;
        string myString = myStreamReader.ReadLine();

        myProcess.WaitForExit();
        myProcess.Close();

        Console.WriteLine("Value received from script: " + myString); 

    }

Python 脚本:-

!/usr/bin/python

导入系统

x = sys.argv[1] 打印(x)

我想以“Archit Panda”的形式输出。 你能告诉我我做错了什么吗?

【问题讨论】:

    标签: c# python-3.x


    【解决方案1】:

    如果您正在接受参数并将其发送给“Archit Panda”,这就像将其发送到命令行一样。

    python blockchain.py Archit Panda

    在您的 Python 脚本中,您只是在寻找 argv[1],即 Archit。 argv[2] 是熊猫。如果你想在你的 Python 脚本中传递参数,要么循环遍历它们,要么你可以在 C# 应用程序中转义空格并发送类似的东西。 "Archit\ Panda""'Archit Panda'"

    命令行选项

    tmp$ python3 test.py Archit Panda Archit tmp$ python3 test.py 'Archit Panda' Archit Panda tmp$ python3 test.py Archit\ Panda Archit Panda tmp$ python3 test.py 'Archit Panda can send a lot of text to this argument.' Archit Panda can send a lot of text to this argument.

    如果你使用引号替换这一行。

    myProcessStartInfo.Arguments = myPythonApp+ " " +str;

    myProcessStartInfo.Arguments = myPythonApp+ " \"" +str+"\"";

    希望这能让你继续前进。

    【讨论】:

    • 谢谢本。但我的问题是我可以从richtextbox 中获取任意数量的字符串。它可以是任意数量的行。我正在将输入读入“str”。我该如何处理?
    • 因此,如果您真的想使用 1 个参数,您可以转义空格或将整个内容放在引号中。 myProcessStartInfo.Arguments = myPythonApp+ " '" +str + "'";
    • 这一行:- myProcessStartInfo.Arguments = myPythonApp + " '" + str + "'"; Console.WriteLine(myProcessStartInfo.Arguments);给出这个:- blockchain.py 'Archit Panda' 输出是:- 从脚本接收的值:'Archit
    • 我尝试了替换方法,我能够将字符串作为一个整体发送。谢谢。
    • 我不得不切换到我的 Windows 机器。而不是 ' 使用 \" 。
    猜你喜欢
    • 2012-02-01
    • 2021-02-27
    • 1970-01-01
    • 2011-07-06
    • 2020-08-22
    • 2022-11-23
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多