简体   繁体   English

如何通过 Python 运行 C# 控制台应用程序?

[英]How to run C# Console Applications via Python?

I've created the following C# Console Application (.NET Core 3.1) with Visual Studio:我使用 Visual Studio 创建了以下C# 控制台应用程序 (.NET Core 3.1)

using System;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            //Check if args contains anything
            if (args.Length > 0)
            {
                Console.WriteLine("args = " + args[0]);
            } else
            {
                Console.WriteLine("args is empty");
            }

            //Prevent the application from closing itself without user input
            string waiter = Console.ReadLine();
        }
    }
}

I am able to execute the application succesfully with one argument via cmd.exe : CMD Input and Output我能够通过cmd.exe使用一个参数成功执行应用程序: CMD 输入和 Output

Now I'd like to run this program with one argument via Python .现在我想通过Python用一个参数运行这个程序。 I've read How to execute a program or call a system command?我读过如何执行程序或调用系统命令? and tried to implement it.并试图实施它。 However, it seems that the application is not being run properly.但是,应用程序似乎没有正常运行。

The python code I am using via Jupyter notebook:我通过 Jupyter 笔记本使用的 python 代码:

import subprocess
path = "C:/Users/duykh/source/repos/ConsoleApp2/ConsoleApp2/bin/Release/netcoreapp3.1/ConsoleApp2.exe"
subprocess.Popen(path) //#Also tried with .call and .run
                        //#subprocess.Popen([path, "argumentexample"]) doesn't work either

Output: Output:

<subprocess.Popen at 0x2bcaeba49a0>

My question would be:我的问题是:

Why is it not being run (properly) and how do I properly run this application with one argument?为什么它没有(正确地)运行,我如何用一个参数正确地运行这个应用程序?

I've answered my own question.我已经回答了我自己的问题。 In a nutshell: I am pretty stupid.简而言之:我很愚蠢。

  1. Jupyter Notebook was running in the background and the application was being run there. Jupyter Notebook 在后台运行,应用程序也在后台运行。 That's why it didn't open a new prompt.这就是它没有打开新提示的原因。

  2. subprocess.Popen([path, "argument example"]) seems to work well for running a console application with an argument as input. subprocess.Popen([path, "argument example"])似乎很适合运行以参数作为输入的控制台应用程序。

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

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